def person(request): if request.method == 'GET': # get one person by name name = request.GET.get('name', ' ') try: person = Person.nodes.get(name=name) response = { "name": person.name, } return JsonResponse(response, safe=False) except: response = {"error": "Error occurred"} return JsonResponse(response, safe=False) if request.method == 'POST': content = request.POST name = content.get('name') password = content.get('password') try: person = Person(name=name, password=password) token = uuid4() person.token = token person.save() response = { "name": person.name, } return JsonResponse(response) except: response = {"error": "Error occurred"} return JsonResponse(response, safe=False)
def get_or_create_person(name): qs = Person.objects.filter(name=name) if qs.count() > 0: return qs[0] else: new_person = Person() new_person.name = name new_person.save() return new_person
def post(self, request, *args, **kwargs): user_data = self.do_graph_request('me') user_friends = self.do_graph_request('me/friends')['data'] ll_access_token_data = self.exchange_long_lived_access_token() # Parse multi level friends dict into single level dict friend_list = {} for friend in user_friends: friend_list[friend['id']] = friend['name'] history = {} existing_friend_list = {} existing_new_friend_list = {} existing_lost_friend_list = {} try: user = Person.objects.get(facebook_id=user_data['id']) history = user.history existing_friend_list = user.friends existing_lost_friend_list = user.lost_friends existing_new_friend_list = user.new_friends except Person.DoesNotExist: user = Person(facebook_id=user_data['id']) # Save long lived access token now = datetime.datetime.now() token_expires = now + datetime.timedelta( seconds=int(ll_access_token_data['expires'])) user.access_token = ll_access_token_data['access_token'] user.access_token_expires_at = token_expires if existing_friend_list: compare_result = compare_dictionaries(existing_friend_list, friend_list) # Merge new and old losts and put them back into the model user.lost_friends = dict( compare_result['removed_entries'].items() + existing_lost_friend_list.items()) user.new_friends = dict(compare_result['added_entries'].items() + existing_new_friend_list.items()) add_entry_to_history(history, len(friend_list)) user.friends = friend_list user.history = history user.save() return HttpResponse(status=200, content=json.dumps({ 'new_friends': user.new_friends, 'lost_friends': user.lost_friends, 'history': user.history }), content_type='application/json')
def create(self,validated_data): name = validated_data.pop('name') qs = Person.objects.filter(name=name) if qs.count() > 0: return qs[0] else: new_person = Person() new_person.name = name new_person.save() print('created person with name %s'%name) return new_person
def create(self, validated_data): name = validated_data.pop('name') qs = Person.objects.filter(name=name) if qs.count() > 0: return qs[0] else: new_person = Person() new_person.name = name new_person.save() logger.info('created person {}' % new_person.id) return new_person
class DummyPerson: person_customer1 = Person(username='******', first_name='first', last_name='last', email='*****@*****.**', person_type=1, password_hashed='password', face=None) person_customer2 = Person(username='******', first_name='first2', last_name='last2', email='*****@*****.**', person_type=1, password_hashed='password', face=None) @staticmethod def create_random() -> Person: return Person(username=uuid4().__str__()[:50], first_name='random', last_name='random', email='*****@*****.**', person_type=1, password_hashed='password', face=None) def creat_random_json(id: int = None): if id is None: return json.dumps({ 'username': uuid4().__str__()[:50], 'first_name': 'first', 'last_name': 'last', 'email': '*****@*****.**', 'person_type': 1, 'password_hashed': 'password', 'face': None }) return json.dumps({ 'id': id, 'username': uuid4().__str__()[:50], 'first_name': 'first', 'last_name': 'last', 'email': '*****@*****.**', 'person_type': 1, 'password_hashed': 'password', })
def writer(header, data, filename, option): with open(filename, "w", newline="") as csvfile: if option == "write": movies = csv.writer(csvfile) movies.writerow(header) for x in data: movies.writerow(x) elif option == "update": writer = csv.DictWriter(csvfile, fieldnames=header) writer.writeheader() writer.writerows(data) else: print("Option is not known") # create SQLAlchemy Objects new_person = Person(name=data["name"]) email = Email(email=data["email"]) new_person.emails.append(email) # commit it to database db.session.add_all([new_person, email]) db.session.commit() return create_response( message= f"Successfully created person {new_person.name} with id: {new_person._id}" )
def create_person(): data = request.get_json() logger.info("Data recieved: %s", data) if "name" not in data: msg = "No name provided for person." logger.info(msg) return create_response(status=422, message=msg) if "email" not in data: msg = "No email provided for person." logger.info(msg) return create_response(status=422, message=msg) # create SQLAlchemy Objects new_person = Person(name=data["name"]) email = Email(email=data["email"]) new_person.emails.append(email) # commit it to database db.session.add_all([new_person, email]) db.session.commit() return create_response( message= f"Successfully created person {new_person.name} with id: {new_person.id}" )
def create_random() -> Person: return Person(username=uuid4().__str__()[:50], first_name='random', last_name='random', email='*****@*****.**', person_type=1, password_hashed='password', face=None)
def create_random() -> Person: return Person(username=uuid4().__str__()[:50], first_name='random', last_name='random', email='*****@*****.**', type=PersonType.CUSTOMER, password=generate_password_hash('password'), face=None)
def quiz_result(): array = request.args.get('array') new_person = Person(cookie=0, saved_topics=array) # commit it to database db.session.add_all([new_person]) db.session.commit() return json.dumps(new_person.id)
def update(self, instance, validated_data): name = validated_data.pop('person')['name'] p = Person.objects.filter(name=name) if p.count() > 0: instance.person = p[0] else: p = Person() p.name = name p.save() instance.person = p print('created person with name %s' % name) if instance.person.name == 'unknown': instance.person_label_is_inferred = None else: instance.person_label_is_inferred = False print('updated label for face %d to %s' % (instance.id, instance.person.name)) instance.save() return instance
def post(self, request, *args, **kwargs): user_data = self.do_graph_request('me') user_friends = self.do_graph_request('me/friends')['data'] ll_access_token_data = self.exchange_long_lived_access_token() # Parse multi level friends dict into single level dict friend_list = {} for friend in user_friends: friend_list[friend['id']] = friend['name'] history = {} existing_friend_list = {} existing_new_friend_list = {} existing_lost_friend_list = {} try: user = Person.objects.get(facebook_id=user_data['id']) history = user.history existing_friend_list = user.friends existing_lost_friend_list = user.lost_friends existing_new_friend_list = user.new_friends except Person.DoesNotExist: user = Person(facebook_id=user_data['id']) # Save long lived access token now = datetime.datetime.now() token_expires = now + datetime.timedelta(seconds=int(ll_access_token_data['expires'])) user.access_token = ll_access_token_data['access_token'] user.access_token_expires_at = token_expires if existing_friend_list: compare_result = compare_dictionaries(existing_friend_list, friend_list) # Merge new and old losts and put them back into the model user.lost_friends = dict(compare_result['removed_entries'].items() + existing_lost_friend_list.items()) user.new_friends = dict(compare_result['added_entries'].items() + existing_new_friend_list.items()) add_entry_to_history(history, len(friend_list)) user.friends = friend_list user.history = history user.save() return HttpResponse(status=200, content=json.dumps({'new_friends': user.new_friends, 'lost_friends': user.lost_friends, 'history': user.history}), content_type='application/json')
def update(self, instance, validated_data): name = validated_data.pop('person')['name'] p = Person.objects.filter(name=name) if p.count() > 0: instance.person = p[0] else: p = Person() p.name = name p.save() instance.person = p print('created person with name %s'%name) if instance.person.name == 'unknown': instance.person_label_is_inferred = None instance.person_label_probability = 0. else: instance.person_label_is_inferred = False instance.person_label_probability = 1. print('updated label for face %d to %s'%(instance.id, instance.person.name)) instance.save() return instance
def update(self, instance, validated_data): name = validated_data.pop('person')['name'] p = Person.objects.filter(name=name) if p.count() > 0: instance.person = p[0] else: p = Person() p.name = name p.save() instance.person = p logger.info('created person with name %s' % name) if instance.person.name == 'unknown': instance.person_label_is_inferred = None instance.person_label_probability = 0. else: instance.person_label_is_inferred = False instance.person_label_probability = 1. logger.info('updated label for face %d to %s' % (instance.id, instance.person.name)) cache.clear() instance.save() return instance
def fill_tables(): r1 = Repository(repository_path="img_dir", repository_type="local") p1 = Person(name="Nick") p2 = Person(name="John") p3 = Person(name="Mary") img1 = Image(image_path="img1.png", repository=r1) img2 = Image(image_path="img2.png", repository=r1) face1 = Face(face_path=".face/f1.png", image=img1, person_by_human=p1, profile_face=True) face2 = Face(face_path=".face/f2.png", image=img1, person_by_human=p2, profile_face=True) # want to check getting unknown faces np_arr = np.array([1, 2, 4, 3], dtype=np.float32) bin_data = pickle.dumps(np_arr) logger.info(bin_data) face3 = Face(face_path=".face/f3.png", image=img2, embedding=bin_data) db.session.add_all([face1, face2, face3]) db.session.commit() return create_response()
def create_person(): data = request.get_json() logger.info("Data recieved: %s", data) if "name" not in data: msg = "No name provided for person." logger.info(msg) return create_response(status=422, message=msg) if "emails" not in data: msg = "No email provided for person." logger.info(msg) return create_response(status=422, message=msg) # create MongoEngine objects new_person = Person(name=data["name"]) for email in data["emails"]: email_obj = Email(email=email) new_person.emails.append(email_obj) new_person.save() return create_response( message=f"Successfully created person {new_person.name} with id: {new_person.id}" )
def test_get_person(client): rs = client.get("/persons") assert rs.status_code == 200 ret_dict = rs.json # gives you a dictionary assert ret_dict["success"] == True assert ret_dict["result"]["persons"] == [] # create Person and test whether it returns a person temp_person = Person(name="Tim") db.session.add(temp_person) db.session.commit() rs = client.get("/persons") ret_dict = rs.json assert len(ret_dict["result"]["persons"]) == 1 assert ret_dict["result"]["persons"][0]["name"] == "Tim"
def save_user(): data = request.form if "id" not in data: msg = "No id provided for person." logger.info(msg) return create_response(status=422, message=msg) if "topics" not in data: msg = "No topics provided for person." logger.info(msg) return create_response(status=422, message=msg) new_person = Person(cookie=data["id"], saved_topics=[json.loads(data["topics"])]) # commit it to database db.session.add_all([new_person]) db.session.commit() return create_response( message= f"Successfully created person {new_person.cookie} with id: {new_person.id}" )
def __scrape_personnel(self): """ Loops through personnel table on company website - Scrapes person data from html elements - If person has already been scraped - Update Person object to include extra relationship - Else - Create Person object and add to database """ table_rows = self.soup.find('tr', {'id': 'Relations_ListView_Tr1'}) table_rows = table_rows.parent.findAll('tr') table_rows = table_rows[1:] # Ignore column names person_dict = {} for index, row in enumerate(table_rows): name = self.__get_soup_value('Relations_ListView_desigLabel_' + str(index)) relationship = self.__get_soup_value( 'Relations_ListView_relLabel_' + str(index)) if name in person_dict.keys(): person = person_dict[name] person = self.__update_person(person, relationship, index) else: person = Person( name=name, company_id=self.company.id, nationality=self.__get_soup_value( 'Relations_ListView_countryLabel_' + str(index)), relationship=relationship, stock=self.__get_soup_value( 'Relations_ListView_a_valLabel_' + str(index), 'int'), quota=self.__get_soup_value( 'Relations_ListView_s_valLabel_' + str(index), 'int'), ratio=self.__get_soup_value( 'Relations_ListView_r_valLabel_' + str(index), 'int')) person_dict[name] = person self.personnel = person_dict.values() Person.objects.bulk_create(self.personnel)
def indexInfoPersonQr(id): person = Person.query.get(id) if person is None: raise APIException('La persona con el id especificado, no fue encontrada.',status_code=403) person = Person.serialize(person) personInfoQr = { "full_name": person["full_name"], "known_as": person["known_as"], "emergency_contact": person["emergency_contact"], "emergency_phone": person["emergency_phone"], "user_image": person["user_image"], "vaccine1_date": person["vaccine1_date"], "vaccine2_date": person["vaccine2_date"] } resultsMedicine = PersonMedicine.query.filter_by(person_id=id) personMedicine = list(map(lambda x: x.serialize(), resultsMedicine)) return jsonify({"results": personInfoQr, "medicine": personMedicine}), 200
def create(fields: dict) -> Person: fields["validate"] = True new_person = Person(**fields) db.session.add(new_person) db.session.commit() return new_person
def post_person(args): person = Person(**args) add_new_obj(person) return create_response(person.to_dict(), 201)
def populate_db(app): with app.app_context(): print('Connecting to db..') db.drop_all() print('Connection successful!') print('db dropped..') db.create_all() db.session.add_all([ cm1, cm2, cm3, ct1, ct2, cc1, cc2, cc3, ]) db.session.commit() print("Required foreign key rows commited..") admin = Person(username='******', first_name='Mr. Admin', last_name='Boss', email='*****@*****.**', type=PersonType.ADMIN, password=generate_password_hash('admin'), face=None) engineer = Person(username='******', first_name='Engineer', last_name='Person', email='*****@*****.**', type=PersonType.ENGINEER, password=generate_password_hash('engineer'), face=None) manager = Person(username='******', first_name='Mr. Manager', last_name='Ad', email='*****@*****.**', type=PersonType.MANAGER, password=generate_password_hash('manager'), face=None) p1 = Person(username='******', first_name='Random', last_name='Person', email='*****@*****.**', type=PersonType.CUSTOMER, password=generate_password_hash('as'), face=None) p2 = Person(username='******', first_name='Adi', last_name='Lastname', email='*****@*****.**', type=PersonType.CUSTOMER, password=generate_password_hash('abc123'), face=None) c1 = Car( reg_number='abc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.8182711', longitude='144.9670618', hour_rate=290.5, ) c2 = Car( reg_number='bbc123', car_manufacturer=cm2.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.8', longitude='144.96667', hour_rate=20.5, ) c3 = Car( reg_number='cbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-38.21792', longitude='145.03876', hour_rate=12.5, ) c4 = Car( reg_number='dbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.98333', longitude='145.2', hour_rate=25.5, ) c5 = Car( reg_number='ebc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.7983459', longitude='144.960974', hour_rate=20.5, ) c6 = Car( reg_number='fbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.829', longitude='144.957', hour_rate=27.5, ) c7 = Car( reg_number='gbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8081201', longitude='144.9644196', hour_rate=11.5, ) c8 = Car( reg_number='hbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.6690123', longitude='144.8410273', hour_rate=99.5, ) c9 = Car( reg_number='ibc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8332233', longitude='144.9124697', hour_rate=30.5, ) c10 = Car( reg_number='jbc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='59.9139', longitude='10.7522', hour_rate=70.5, ) c11 = Car( reg_number='kbc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.7923459', longitude='144.960974', hour_rate=20.5, ) c12 = Car( reg_number='lbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8678765', longitude='144.9740049', hour_rate=20.5, ) c13 = Car( reg_number='mbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-38.21792', longitude='144.960974', hour_rate=50.5, ) c14 = Car( reg_number='nbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.7983459', longitude='144.960974', hour_rate=20.5, ) c15 = Car( reg_number='obc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='37.7983459', longitude='144.320974', hour_rate=20.5, ) c16 = Car( reg_number='pbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='59.9139', longitude='144.110974', hour_rate=20.5, ) c17 = Car( reg_number='qbc123', car_manufacturer=cm3.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='37.7183459', longitude='144.230974', hour_rate=20.5, ) c18 = Car( reg_number='rbc123', car_manufacturer=cm3.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.3983459', longitude='144.460974', hour_rate=20.5, ) c19 = Car( reg_number='sbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.283459', longitude='144.990974', hour_rate=20.5, ) c20 = Car( reg_number='tbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.829', longitude='144.930974', hour_rate=20.5, ) db.session.add_all([ admin, engineer, manager, p1, p2, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20 ]) db.session.commit() b1 = Booking( car_id=c1.id, person_id=p1.id, start_time=datetime.now().replace(microsecond=0, second=0) - timedelta(days=4), end_time=datetime.now().replace(microsecond=0, second=0) - timedelta(days=2), status=BookingStatusEnum.CANCELLED) b2 = Booking( car_id=c2.id, person_id=p1.id, start_time=datetime.now().replace(microsecond=0, second=0) - timedelta(days=1), end_time=datetime.now().replace(microsecond=0, second=0) - timedelta(hours=10), status=BookingStatusEnum.FINISHED) i1 = CarIssue(car_id=c1.id, issue='There are no tiers') i2 = CarIssue(car_id=c2.id, issue='The engine is gone') i3 = CarIssue(car_id=c3.id, issue='Can only drive backwards') i4 = CarIssue(car_id=c4.id, issue='Totalled') db.session.add_all([b1, b2, i1, i2, i3, i4]) db.session.commit() print('All data commited!') print('Finished!')
def on_post(self, req, resp): body = json.loads(req.stream.read(), object_hook=lambda d: Namespace(**d)) session.add(Person(name=body.name, age=body.age)) session.commit() session.close()
def create(self, validated_data): person = Person(**validated_data) password = self.validated_data['password'] person.set_password(password) person.save() return person
def load_fake_data(): Person.objects.all().delete() data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "$320,800", "start_date": "2011\/04\/25", "office": "Edinburgh", "extn": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "$170,750", "start_date": "2011\/07\/25", "office": "Tokyo", "extn": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "$86,000", "start_date": "2009\/01\/12", "office": "San Francisco", "extn": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "$433,060", "start_date": "2012\/03\/29", "office": "Edinburgh", "extn": "6224" }, { "name": "Airi Satou", "position": "Accountant", "salary": "$162,700", "start_date": "2008\/11\/28", "office": "Tokyo", "extn": "5407" }, { "name": "Brielle Williamson", "position": "Integration Specialist", "salary": "$372,000", "start_date": "2012\/12\/02", "office": "New York", "extn": "4804" }, { "name": "Herrod Chandler", "position": "Sales Assistant", "salary": "$137,500", "start_date": "2012\/08\/06", "office": "San Francisco", "extn": "9608" }, { "name": "Rhona Davidson", "position": "Integration Specialist", "salary": "$327,900", "start_date": "2010\/10\/14", "office": "Tokyo", "extn": "6200" }, { "name": "Colleen Hurst", "position": "Javascript Developer", "salary": "$205,500", "start_date": "2009\/09\/15", "office": "San Francisco", "extn": "2360" }, { "name": "Sonya Frost", "position": "Software Engineer", "salary": "$103,600", "start_date": "2008\/12\/13", "office": "Edinburgh", "extn": "1667" }, { "name": "Jena Gaines", "position": "Office Manager", "salary": "$90,560", "start_date": "2008\/12\/19", "office": "London", "extn": "3814" }, { "name": "Quinn Flynn", "position": "Support Lead", "salary": "$342,000", "start_date": "2013\/03\/03", "office": "Edinburgh", "extn": "9497" }, { "name": "Charde Marshall", "position": "Regional Director", "salary": "$470,600", "start_date": "2008\/10\/16", "office": "San Francisco", "extn": "6741" }, { "name": "Haley Kennedy", "position": "Senior Marketing Designer", "salary": "$313,500", "start_date": "2012\/12\/18", "office": "London", "extn": "3597" }, { "name": "Tatyana Fitzpatrick", "position": "Regional Director", "salary": "$385,750", "start_date": "2010\/03\/17", "office": "London", "extn": "1965" }, { "name": "Michael Silva", "position": "Marketing Designer", "salary": "$198,500", "start_date": "2012\/11\/27", "office": "London", "extn": "1581" }, { "name": "Paul Byrd", "position": "Chief Financial Officer (CFO)", "salary": "$725,000", "start_date": "2010\/06\/09", "office": "New York", "extn": "3059" }, { "name": "Gloria Little", "position": "Systems Administrator", "salary": "$237,500", "start_date": "2009\/04\/10", "office": "New York", "extn": "1721" }, { "name": "Bradley Greer", "position": "Software Engineer", "salary": "$132,000", "start_date": "2012\/10\/13", "office": "London", "extn": "2558" }, { "name": "Dai Rios", "position": "Personnel Lead", "salary": "$217,500", "start_date": "2012\/09\/26", "office": "Edinburgh", "extn": "2290" }, { "name": "Jenette Caldwell", "position": "Development Lead", "salary": "$345,000", "start_date": "2011\/09\/03", "office": "New York", "extn": "1937" }, { "name": "Yuri Berry", "position": "Chief Marketing Officer (CMO)", "salary": "$675,000", "start_date": "2009\/06\/25", "office": "New York", "extn": "6154" }, { "name": "Caesar Vance", "position": "Pre-Sales Support", "salary": "$106,450", "start_date": "2011\/12\/12", "office": "New York", "extn": "8330" }, { "name": "Doris Wilder", "position": "Sales Assistant", "salary": "$85,600", "start_date": "2010\/09\/20", "office": "Sidney", "extn": "3023" }, { "name": "Angelica Ramos", "position": "Chief Executive Officer (CEO)", "salary": "$1,200,000", "start_date": "2009\/10\/09", "office": "London", "extn": "5797" }, { "name": "Gavin Joyce", "position": "Developer", "salary": "$92,575", "start_date": "2010\/12\/22", "office": "Edinburgh", "extn": "8822" }, { "name": "Jennifer Chang", "position": "Regional Director", "salary": "$357,650", "start_date": "2010\/11\/14", "office": "Singapore", "extn": "9239" }, { "name": "Brenden Wagner", "position": "Software Engineer", "salary": "$206,850", "start_date": "2011\/06\/07", "office": "San Francisco", "extn": "1314" }, { "name": "Fiona Green", "position": "Chief Operating Officer (COO)", "salary": "$850,000", "start_date": "2010\/03\/11", "office": "San Francisco", "extn": "2947" }, { "name": "Shou Itou", "position": "Regional Marketing", "salary": "$163,000", "start_date": "2011\/08\/14", "office": "Tokyo", "extn": "8899" }, { "name": "Michelle House", "position": "Integration Specialist", "salary": "$95,400", "start_date": "2011\/06\/02", "office": "Sidney", "extn": "2769" }, { "name": "Suki Burks", "position": "Developer", "salary": "$114,500", "start_date": "2009\/10\/22", "office": "London", "extn": "6832" }, { "name": "Prescott Bartlett", "position": "Technical Author", "salary": "$145,000", "start_date": "2011\/05\/07", "office": "London", "extn": "3606" }, { "name": "Gavin Cortez", "position": "Team Leader", "salary": "$235,500", "start_date": "2008\/10\/26", "office": "San Francisco", "extn": "2860" }, { "name": "Martena Mccray", "position": "Post-Sales support", "salary": "$324,050", "start_date": "2011\/03\/09", "office": "Edinburgh", "extn": "8240" }, { "name": "Unity Butler", "position": "Marketing Designer", "salary": "$85,675", "start_date": "2009\/12\/09", "office": "San Francisco", "extn": "5384" }, { "name": "Howard Hatfield", "position": "Office Manager", "salary": "$164,500", "start_date": "2008\/12\/16", "office": "San Francisco", "extn": "7031" }, { "name": "Hope Fuentes", "position": "Secretary", "salary": "$109,850", "start_date": "2010\/02\/12", "office": "San Francisco", "extn": "6318" }, { "name": "Vivian Harrell", "position": "Financial Controller", "salary": "$452,500", "start_date": "2009\/02\/14", "office": "San Francisco", "extn": "9422" }, { "name": "Timothy Mooney", "position": "Office Manager", "salary": "$136,200", "start_date": "2008\/12\/11", "office": "London", "extn": "7580" }, { "name": "Jackson Bradshaw", "position": "Director", "salary": "$645,750", "start_date": "2008\/09\/26", "office": "New York", "extn": "1042" }, { "name": "Olivia Liang", "position": "Support Engineer", "salary": "$234,500", "start_date": "2011\/02\/03", "office": "Singapore", "extn": "2120" }, { "name": "Bruno Nash", "position": "Software Engineer", "salary": "$163,500", "start_date": "2011\/05\/03", "office": "London", "extn": "6222" }, { "name": "Sakura Yamamoto", "position": "Support Engineer", "salary": "$139,575", "start_date": "2009\/08\/19", "office": "Tokyo", "extn": "9383" }, { "name": "Thor Walton", "position": "Developer", "salary": "$98,540", "start_date": "2013\/08\/11", "office": "New York", "extn": "8327" }, { "name": "Finn Camacho", "position": "Support Engineer", "salary": "$87,500", "start_date": "2009\/07\/07", "office": "San Francisco", "extn": "2927" }, { "name": "Serge Baldwin", "position": "Data Coordinator", "salary": "$138,575", "start_date": "2012\/04\/09", "office": "Singapore", "extn": "8352" }, { "name": "Zenaida Frank", "position": "Software Engineer", "salary": "$125,250", "start_date": "2010\/01\/04", "office": "New York", "extn": "7439" }, { "name": "Zorita Serrano", "position": "Software Engineer", "salary": "$115,000", "start_date": "2012\/06\/01", "office": "San Francisco", "extn": "4389" }, { "name": "Jennifer Acosta", "position": "Junior Javascript Developer", "salary": "$75,650", "start_date": "2013\/02\/01", "office": "Edinburgh", "extn": "3431" }, { "name": "Cara Stevens", "position": "Sales Assistant", "salary": "$145,600", "start_date": "2011\/12\/06", "office": "New York", "extn": "3990" }, { "name": "Hermione Butler", "position": "Regional Director", "salary": "$356,250", "start_date": "2011\/03\/21", "office": "London", "extn": "1016" }, { "name": "Lael Greer", "position": "Systems Administrator", "salary": "$103,500", "start_date": "2009\/02\/27", "office": "London", "extn": "6733" }, { "name": "Jonas Alexander", "position": "Developer", "salary": "$86,500", "start_date": "2010\/07\/14", "office": "San Francisco", "extn": "8196" }, { "name": "Shad Decker", "position": "Regional Director", "salary": "$183,000", "start_date": "2008\/11\/13", "office": "Edinburgh", "extn": "6373" }, { "name": "Michael Bruce", "position": "Javascript Developer", "salary": "$183,000", "start_date": "2011\/06\/27", "office": "Singapore", "extn": "5384" }, { "name": "Donna Snider", "position": "Customer Support", "salary": "$112,000", "start_date": "2011\/01\/25", "office": "New York", "extn": "4226" } ] for p in data: print "p", p new_p = Person(**p) new_p.save()
def get_persons(): persons = Person.objects() return create_response(data={"persons": persons})
def person(): if request.method == 'GET': person_list = cache.get('person_list') if person_list is not None: return make_response(jsonify( { 'message': 'Success', 'data': {'person_list': person_list} }), 200) person_list = Person.query.order_by(Person.create_date).all() schema = PersonSchema(many=True) result = schema.dump(person_list) cache.set('person_list', result, helper.get_hours_in_seconds(1)) return make_response(jsonify( { 'message': 'Success', 'data': {'person_list': result} }), 200) if request.method == 'POST': if helper.is_empty_content_length(request): app.logger.error(f'Exception: {request.content_type}') return make_response(jsonify( { 'message': 'Payload can not be empty' }), 411) if not helper.is_json_content(request): app.logger.error(f'Exception: {request.content_type}') return make_response(jsonify( { 'message': 'Unsupported Media Type' }), 415) name = request.json['name'] email = request.json['email'] if name or email: _person = Person(name=name, email=email) try: db.session.add(_person) db.session.commit() except Exception as err: app.logger.error(f'Exception: {err}') return make_response(jsonify( { 'message': 'Error while creating person! That email address is already in use.' }), 500) else: return make_response(jsonify( { 'message': 'Name or email is missing.' }), 200) cache.delete('person_list') return make_response(jsonify( { 'message': 'Success!', 'data': {'person_id': _person.id} }), 200)
def populate_db(app): with app.app_context(): print('Connecting to db..') db.drop_all() print('Connection successful!') print('db dropped..') db.create_all() db.session.add_all([ pt1, cm1, cm2, cm3, ct1, ct2, cc1, cc2, cc3, ]) db.session.commit() print("Required foreign key rows commited..") p1 = Person(username='******', first_name='Adi', last_name='Lastname', email='*****@*****.**', person_type=pt1.id, password_hashed='password', face=None) c1 = Car( reg_number='abc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.8182711', longitude='144.9670618', hour_rate=290.5, ) c2 = Car( reg_number='bbc123', car_manufacturer=cm2.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.8', longitude='144.96667', hour_rate=20.5, ) c3 = Car( reg_number='cbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-38.21792', longitude='145.03876', hour_rate=12.5, ) c4 = Car( reg_number='dbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.98333', longitude='145.2', hour_rate=25.5, ) c5 = Car( reg_number='ebc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.7983459', longitude='144.960974', hour_rate=20.5, ) c6 = Car( reg_number='fbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.829', longitude='144.957', hour_rate=27.5, ) c7 = Car( reg_number='gbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8081201', longitude='144.9644196', hour_rate=11.5, ) c8 = Car( reg_number='hbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.6690123', longitude='144.8410273', hour_rate=99.5, ) c9 = Car( reg_number='ibc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8332233', longitude='144.9124697', hour_rate=30.5, ) c10 = Car( reg_number='jbc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='59.9139', longitude='10.7522', hour_rate=70.5, ) c11 = Car( reg_number='kbc123', car_manufacturer=cm1.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.7923459', longitude='144.960974', hour_rate=20.5, ) c12 = Car( reg_number='lbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc2.id, seats=4, latitude='-37.8678765', longitude='144.9740049', hour_rate=20.5, ) c13 = Car( reg_number='mbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-38.21792', longitude='144.960974', hour_rate=50.5, ) c14 = Car( reg_number='nbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='-37.7983459', longitude='144.960974', hour_rate=20.5, ) c15 = Car( reg_number='obc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='37.7983459', longitude='144.320974', hour_rate=20.5, ) c16 = Car( reg_number='pbc123', car_manufacturer=cm3.id, car_type=ct1.id, car_colour=cc1.id, seats=4, latitude='59.9139', longitude='144.110974', hour_rate=20.5, ) c17 = Car( reg_number='qbc123', car_manufacturer=cm3.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='37.7183459', longitude='144.230974', hour_rate=20.5, ) c18 = Car( reg_number='rbc123', car_manufacturer=cm3.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.3983459', longitude='144.460974', hour_rate=20.5, ) c19 = Car( reg_number='sbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.283459', longitude='144.990974', hour_rate=20.5, ) c20 = Car( reg_number='tbc123', car_manufacturer=cm1.id, car_type=ct2.id, car_colour=cc1.id, seats=4, latitude='-37.829', longitude='144.930974', hour_rate=20.5, ) db.session.add_all([ p1, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20 ]) db.session.commit() print('All data commited!') print('Finished!')
def test_person_exists(self): # Does our person_exists() model function work? self.assertIs(Person.person_exists(12345), True)
def register(): data_request = request.get_json() user = User.query.filter_by(email=data_request["email"]).first() # Se valida que el email no haya sido registrado.s if user: return jsonify( {"message": "Ya existe una cuenta asociada a ese email."}), 401 user = User(name=data_request["name"], first_surname=data_request["first_surname"], second_surname=data_request["second_surname"], birth_date=data_request["birth_date"], telephone_number=data_request["telephone_number"], user_image=data_request["user_image"], email=data_request["email"], password=data_request["password"], active=data_request["active"], creation_date=datetime.datetime.now(), update_date=datetime.datetime.now()) try: db.session.add(user) db.session.commit() # Se crea una persona con los mismos datos del usuario que se esta registrando userInfo = User.serialize(user) person = Person(name=data_request["name"], first_surname=data_request["first_surname"], second_surname=data_request["second_surname"], known_as="", birth_date=data_request["birth_date"], telephone_number=data_request["telephone_number"], user_image="", emergency_contact="", emergency_phone="", user_creation_id=userInfo["id"], creation_date=datetime.datetime.now(), update_date=datetime.datetime.now()) db.session.add(person) db.session.commit() nombreBienvenida = data_request["name"] + " " + data_request[ "first_surname"] nombreBienvenida = app.processString(nombreBienvenida) # Se envia correo de bienvenida al usuario que se esta registrando. # app.send_email(subject='Bienvenido(a) a medicQR', # sender=current_app.config['DONT_REPLY_FROM_EMAIL'], # recipients=[data_request["email"]], # text_body=f'Hola {nombreBienvenida}, bienvenido(a) a medicQR', # html_body=f'<p>Hola <strong>{nombreBienvenida}</strong>, bienvenido(a) a medicQR.</p>') app.send_email_gmail(subject='Bienvenido(a) a medicQR', to=data_request["email"], text_body='Hola ' + nombreBienvenida + ', bienvenido(a) a medicQR') return jsonify(User.serialize(user)), 201 except AssertionError as exception_message: return jsonify(msg='Error: {}. '.format(exception_message)), 400