def read_value(self, request): """ Get the entity based on its string value(if multiple entities are found the first one is fetched). If the entity does not exist it creates a new one and returns its string value and id. :param request: :return: """ try: current_user = endpoints.get_current_user() if current_user is None: raise endpoints.UnauthorizedException('User not authenticated.') gae_response = GaeResponse() # get the entity from the string if not request.string_value: entity = None else: entity_list = Entity.query(Entity.string_value == request.string_value).fetch(1) if len(entity_list) != 0: entity = entity_list[0] else: entity = None if entity == None: entity = Entity(string_value=request.string_value) entity.put() entity_urlsafe = entity.key.urlsafe() gae_response.id_value = '{0}'.format(entity_urlsafe) gae_response.string_value = '{0}'.format(entity.string_value) return gae_response except Exception as ex: raise endpoints.NotFoundException('Couldn''t handle a GET request, ex:' + ex.message)
def get(self): r = dict() r["/help"] = "[GET] Lists all available API calls to the generator" r["/car-sim"] = "Car simulator API" r["/car-sim/generate"] = "[POST] Call to generate Car Simulator game" e = Entity(status=Status.SUCCESS, data=r) return e.to_dict()
def update(entity: Entity) -> Entity: """ Update and return entity. """ entity.set_modified() database.session.commit() return entity
def delete(entity: Entity) -> Entity: """ Delete and return entity. """ entity.set_deleted() database.session.commit() return entity
def get(self): """Description: Helper GET call to list all Python specific API calls in Generator :return: Dictionary with path and description values """ r = dict() r["/api/python"] = "GET: General API information containing python specific calls" r["/api/python/generate"] = "POST: Python code generator from blueprint json strings" e = Entity(status=Status.SUCCESS, data=r) return e.to_dict()
def get(self, name): """Description: GET generate python project from registered project :param name: Project name to generate from :return: Entity object with request status """ p = ProjectManager.get_project(name) e = Entity() if p is not None: e.status = PythonGenerator.generate(p) else: e.status = Status.GENERATION_FAILED return e.to_dict()
def post(self): """Description: POST register project :return: Registration status """ e = Entity() if isinstance(flask_restful.request.get_json(), str): data = json.loads(flask_restful.request.get_json()) elif isinstance(flask_restful.request.get_json(), dict): data = flask_restful.request.get_json() else: data = dict() p = ProjectManager.create_project(data) e.status = ProjectManager.add_project(p) return e.to_dict()
def write_value(self, request): """ Get the first entity with the provided string value, if the entity already exists in the datastore (if multiple entities are found the first one is fetched), returns the string value and the entity's id. Raise exception if entity does not exist. :param request: :return: """ try: current_user = endpoints.get_current_user() if current_user is None: raise endpoints.UnauthorizedException('User not authenticated.') gae_response = GaeResponse() # get the entity from the string if not request.string_value: entity = None else: entity_list = Entity.query(Entity.string_value == request.string_value).fetch(1) if len(entity_list) != 0: entity = entity_list[0] else: entity = None if entity == None: raise endpoints.BadRequestException('Resource with string value {0} not found'.format(request.string_value)) entity_urlsafe = entity.key.urlsafe() gae_response.id_value = '{0}'.format(entity_urlsafe) gae_response.string_value = '{0}'.format(entity.string_value) return gae_response except Exception as ex: raise endpoints.NotFoundException('Couldn''t handle a POST request, ex:' + ex.message)
def toDict(self): repre = Entity.toDict(self) repre.update({ 'username': self.username, }) # no need to send the password as it would not be transmitted return repre
def CreateEntity(value, note_id): new_entity = Entity( value = value, note_id = note_id ) db.session.add(new_entity) db.session.commit()
def put(self, name): """Description: PUT updates project and it`s content :param name: Project name :return: Request status """ e = Entity() p = ProjectManager.get_project(name) if isinstance(flask_restful.request.get_json(), str): data = json.loads(flask_restful.request.get_json()) elif isinstance(flask_restful.request.get_json(), dict): data = flask_restful.request.get_json() else: data = dict() e.status = ProjectManager.update_project(p, data) return e.to_dict()
def get(self, name=None): """Description: GET single project by name or all registered projects :param name: <<Optional>> project name :return: Project JSON response """ if name is None: r = list() for p in ProjectManager.PROJECTS: r.append(p.to_dict()) else: r = ProjectManager.get_project(name) r = r.to_dict() e = Entity(status=Status.SUCCESS, data=r) return e.to_dict()
def parse_brat(file_path, encoding): entities_list, references_list = [], [] file = codecs.open(file_path, 'r', encoding=encoding) lines = file.readlines() text = read_doc(file_path.replace('ann', 'txt'), encoding) for line in lines: if line.startswith('R'): id, relation_info = re.split('\t', line)[:2] relation_type, arg1, arg2 = relation_info.split(' ') refA = arg1.split(':')[1].replace('T', '') refB = arg2.split(':')[1].replace('T', '') entities = [ filter(lambda ent: ent.id == int(refA), entities_list)[0], filter(lambda ent: ent.id == int(refB), entities_list)[0] ] ent1, ent2 = entities _sentence_ = get_sentence_in_entities(text, ent1, ent2) kwargs_for_relation = { 'id': int(id.replace('R', '')), 'type': relation_type, 'refA': int(refA), 'refB': int(refB), 'refAobj': filter(lambda ent: ent.id == int(refA), entities_list)[0], 'refBobj': filter(lambda ent: ent.id == int(refB), entities_list)[0], 'text': _sentence_, 'text_between': text[ent1.index_b:ent2.index_a], 'tokenized_text_between': word_tokenize(text[ent1.index_b:ent2.index_a]), } references_list.append(Reference(**kwargs_for_relation)) elif line.startswith('T'): fields = re.split("\t+", line) id = fields[0].replace('T', '') entity_type, indexA = fields[1].split(' ')[:2] indexB = fields[1].split(' ')[-1] value = fields[2].replace('\n', '') kwargs_for_entity = { 'id': int(id), 'length': int(indexB) - int(indexA), 'index_a': int(indexA), 'index_b': int(indexB), 'value': value, 'type': entity_type, } entities_list.append(Entity(**kwargs_for_entity)) return entities_list, references_list
def parse_xml(file_path, encoding): text = read_doc( file_path.replace('annotations', 'corpus').replace('.bioc.xml', ''), encoding) entities_list, references_list = ([], []) tree = ET.parse(file_path).getroot() entities = tree._children[3]._children[1]._children[1:] for entity in entities: if entity.tag == "annotation": xml_fields_obj = XML_field.get_params_for_entity(entity) kwargs_for_entity = { 'id': int(entity.attrib['id']), 'length': xml_fields_obj.length, 'index_a': xml_fields_obj.index, 'index_b': xml_fields_obj.index + xml_fields_obj.length, 'value': xml_fields_obj.value, 'type': xml_fields_obj.type, } entities_list.append(Entity(**kwargs_for_entity)) elif entity.tag == 'relation': xml_fields_obj = XML_field.get_params_for_relation(entity) entities = [ filter(lambda ent: ent.id == xml_fields_obj.ref_id[0], entities_list)[0], filter(lambda ent: ent.id == xml_fields_obj.ref_id[1], entities_list)[0] ] ent1, ent2 = entities _sentence_ = get_sentence_in_entities(text, ent1, ent2) kwargs_for_relation = { 'id': int(entity.attrib['id']), 'type': xml_fields_obj.type, 'refA': xml_fields_obj.ref_id[0], 'refB': xml_fields_obj.ref_id[1], 'refAobj': ent1, 'refBobj': ent2, 'text': _sentence_, 'text_between': text[ent1.index_b:ent2.index_a], 'tokenized_text_between': word_tokenize(text[ent1.index_b:ent2.index_a]), } references_list.append(Reference(**kwargs_for_relation)) XML_field.ref_id = [] return entities_list, references_list
def toDict(self): repre = Entity.toDict(self) repre.update({ 'name': self.name, 'hp': self.hp, 'type_1': self.type_1, 'type_2': self.type_2, 'attack': self.attack, 'defense': self.defense, 'special_attack': self.special_attack, 'special_defense': self.special_defense, 'total': self.total, 'speed': self.speed }) return repre
def __init__(self): super().__init__() Entity.__init__(self)
def post(self): e = Entity() if not request.is_json: e.status = Status.FAILED e.data = {"MESSAGE": "Missing JSON request body"} return e.to_dict(), 400 usr = request.json.get("USERNAME", None) pwd = request.json.get("PASSWORD", None) if usr is None or pwd is None: e.status = Status.FAILED e.data = { "MESSAGE": "Missing one of the login parameters", "USERNAME": usr, "PASSWORD": pwd } return e.to_dict(), 400 else: for u in USERS: if u.get("USERNAME") == usr and u.get("PASSWORD") == pwd: token = create_access_token(identity=usr) e.status = Status.SUCCESS e.data = {"TOKEN": token} break else: e.status = Status.SUCCESS e.data = {"MESSAGE": "User is not authorized to access API"} return e.to_dict(), 200
def __init__(self, username, password, role=0): super().__init__() Entity.__init__(self) self.username = username self.password = password