def from_web(item, cities): if not item['data0']: return None obj = Submission() obj.name = PersonName({ 'last_name': item['data0'], 'first_name': item['data1'], 'middle_name': item['data2'], 'name_suffix': item['data3'] }) try: obj.address = Address({ 'address': item['data4'], 'city': item['data5'], 'zipcode': item['data6'] }) except Exception as ex: if str(ex).startswith('Unable to parse address'): obj.address = Address({ 'address': "", 'city': item['data5'], 'zipcode': item['data6'] }) if obj.address.city not in cities: for city in cities: if city['zipcode'] == obj.address.zipcode: obj.address.city = city['name'] break return obj
def test_successful_catalog(self): address_data = { "street": "primera", "city": "segunda", "state": "tercero", "country": "cuarto", "name_code": "123abc" } address = Address(**address_data) address.save() shop_data = { "name": "un ejemplo mas", "address_id": address.id } shop = Shop(**shop_data) shop.save() # Given payload = json.dumps({ "name": "prueba", "shop_id": shop.id }) # When response = self.app.post( '/api/v1/catalog/', headers={"Content-Type": "application/json"}, data=payload ) # Then self.assertEqual(dict, type(response.json)) self.assertEqual(201, response.status_code)
def read_coordinate_input(coordinate_string): coordinates = coordinate_string.split(",") assert len(coordinates) == 2, \ "coordinate input should be a string as follows '<latitude>, <longitude>' " address = Address() address.latitude = coordinates[0].strip() address.longitude = coordinates[1].strip() return __get_list_from_single_address(address)
def test_as_json(mockEngine, mock_address_request_data): request_data = mock_address_request_data.copy() address = Address(**request_data) request_data['created_at'] = None request_data['last_updated'] = None assert address.as_json() == request_data
def test_successful_inventory(self): address_data = { "street": "primera", "city": "segunda", "state": "tercero", "country": "cuarto", "name_code": "123abc" } address = Address(**address_data) address.save() shop_data = {"name": "un ejemplo mas", "address_id": address.id} shop = Shop(**shop_data) shop.save() catalog_data = {"name": "primavera verano", "shop_id": shop.id} catalog = Catalog(**catalog_data) catalog.save() product_data = { "title": "p2", "description": "un articulo de ropa", "price": 2.2, "is_featured": True, "sku": "abc12345678", "catalog_id": catalog.id, } product = Product(**product_data) product.save() inventory_data = { "product_id": product.id, "quantity": 10, "shop_id": shop.id } inventory = Inventory(**inventory_data) inventory.save() # Given payload = json.dumps({ "sku": "abc12345678", "quantity": 10, "shop_id": shop.id }) # When response = self.app.post('/api/v1/inventory/', headers={"Content-Type": "application/json"}, data=payload) # Then self.assertEqual(dict, type(response.json)) self.assertEqual(200, response.status_code)
def read_address_input(infile): """Read input address csv into list of address objects.""" with open(infile, newline='') as csv_address_infile: csvReader = csv.reader(csv_address_infile, delimiter=',') __check_address_input(csvReader) address_object_list = [] for row in csvReader: address_string = str(row[0]) if address_string: address = Address() address.input_string = address_string address_object_list.append(address) return address_object_list
def profile_worker(person_id): """ Worker profile edit profile form """ print("profile worker", request.method) if request.method == "POST": print("mijo") info = request.form contacts = storage.all(Contact_info) number = None for contact in contacts.values(): if contact.person == person_id: number = contact if number is None: number = Contact_info() number.person = person_id number.type_contact = info['type-contact'] number.data_contact = info['data-contact'] addresses = storage.all(Address) add = None for adding in addresses.values(): if adding.person == person_id: add = adding if add is None: add = Address() add.address = info['address'] add.person = person_id objects = storage.all(Person) obj = None for ob in objects.values(): if ob.id == person_id: obj = storage.get(User, ob.user) if obj is None: obj = User() obj.email = info['email'] obj.psswd = info['password'] mka = storage mka.new(number) mka.save() mka.new(add) mka.save() mka.new(obj) mka.save() mka.close() return redirect('/profile-worker/{}'.format(obj.id), code=302) print(person_id) return render_template('profile_worker.html', id=str(uuid.uuid4()), person_id=person_id)
def read_coordinate_input(infile): """Read input coordinate csv into list of address objects.""" with open(infile, newline='') as csv_address_infile: csvReader = csv.reader(csv_address_infile, delimiter=',') __check_coordinate_input(csvReader) address_object_list = [] for row in csvReader: latitude = str(row[0]) longitude = str(row[1]) if latitude and longitude: address = Address() address.latitude = latitude address.longitude = longitude address_object_list.append(address) return address_object_list
def show_users_address(address_id): try: address = Address.get(Address.id == address_id) # throws a access denied error if the user is not the owner of the address instance try: if not address.user_is_owner(current_user.id): raise ResourceAccessDenied() except ResourceAccessDenied as e: return e.get_json_response() address_dict = model_to_dict(address) del address_dict['user']['password'] return jsonify( data=address_dict, status={ 'code': 200, 'message': 'Successfully got resource.' } ) except DoesNotExist: return jsonify( data={}, status={ 'code': 404, 'message': 'Resource does not exist.' } )
def delete_address(address_id): try: address_to_delete = Address.get(Address.id == address_id) # checks if the user is the creator of the address, if not an exception is thrown try: if not address_to_delete.user_is_owner(current_user.id): raise ResourceAccessDenied() except ResourceAccessDenied as e: return e.get_json_response() # after the user of the model instance is verified then its deleted address_to_delete.delete_instance() return jsonify( data={}, status={ 'code': 204, 'message': 'Resource deleted successfully.' } ) except DoesNotExist: return jsonify( data={}, status={ 'code': 404, 'message': 'Resource does not exist' } )
def get_users_addresses(): try: all_addresses = Address.select().where(Address.user == current_user.id) # converts the address model instances to dictionaries all_addresses_dict = [model_to_dict(address) for address in all_addresses] # iterates through all the model instances and converts them to a dictionary and removes # the users password all_addresses_dict = [] for address in all_addresses: address_dict = model_to_dict(address) del address_dict['user']['password'] all_addresses_dict.append(address_dict) return jsonify( data=all_addresses_dict, status={ 'code': 200, 'message': 'Successfully found resources.' } ) except DoesNotExist: return jsonify( data={}, status={ 'code': 404, 'message': 'Resource does not exist.' } )
def luuChinhSuaThongTinB(): if session["type_account"] != "renter": return password = str(request.get_json()["password"]) repassword = str(request.get_json()["repassword"]) fullname = str(request.get_json()["fullname"]) phoneNumber = str(request.get_json()["phoneNumber"]) email = str(request.get_json()["email"]) birthday = str(request.get_json()["birthday"]) addressProvince = str(request.get_json()["addressProvince"]) addressDistrict = str(request.get_json()["addressDistrict"]) addressWard = str(request.get_json()["addressWard"]) addressDetail = str(request.get_json()["addressDetail"]) typeAvt = int(request.get_json()["typeAvt"]) typeAccount = session["type_account"] if password != repassword or not Address.checkAddress( addressProvince, addressDistrict, addressWard) or not CheckValidation.isFullname( fullname) or not CheckValidation.isPhoneNumber( phoneNumber) or not CheckValidation.isEmail(email): return Renter().editAccount(session["username"], password, phoneNumber, email, birthday, addressProvince, addressDistrict, addressWard, addressDetail, typeAvt) return app.response_class(json.dumps({"message": "ok"}), mimetype='application/json')
def get_person_info(person_id): """ Method that gets info to post in edit profile form filled fields """ print("getting user info") contacts = storage.all(Contact_info) for contact in contacts.values(): if contact.person == person_id: number = contact if number is None: number = Contact_info() addresses = storage.all(Address) for adding in addresses.values(): if adding.person == person_id: add = adding if add is None: add = Address() objects = storage.all(Person) for ob in objects.values(): if ob.id == person_id: obj = storage.get(User, ob.user) if obj is None: obj = User() resp = {} resp['contact'] = number.type_contact resp['address'] = add.address resp['user'] = obj.email print(resp) return jsonify(resp), 200
def getAddressById(self, add_id): dao = AddressesDAO() row = dao.getAddressById(add_id) if not row: return jsonify(Error="Address Not Found"), 404 else: address = Address().build_dict_from_row(row) return jsonify(address)
def lookup(dao, params): pn = PersonName(params) if 'address' in params and params['address']: addr = Address(params) matches = Voter.voters_by_name_and_address(dao, addr, pn) if matches: return matches return Voter.__voters_by_name(dao, pn)
def getSuppliersCountPerRegion(self): dao = SuppliersDAO() counts_list = dao.getSuppliersCountPerRegion() result_list = [] for row in counts_list: count = Address().build_dict_from_row_count(row) result_list.append(count) return jsonify(result_list)
def __init__(self, d=None): self.id = None self.name = None self.birth_year = None self.gender = '' self.info = None self.address = None self.voter_id = None self.reg_date = '' self.precinct_id = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d) self.info = ContactInfo(d)
def getAllAddresses(self): dao = AddressesDAO() users_list = dao.getAllAddresses() result_list = [] for row in users_list: address = Address().build_dict_from_row(row) result_list.append(address) return jsonify(result_list)
def test_get_best_voter(self): addr = Address({'address': '3000 Newcastle Rd'}) pn = PersonName({'last_name': 'weinblatt', 'first_name': 'howard'}) contact = Contact() contact.name = pn contact.address = addr voter = Contact.get_best_voter_rec(self.dao, contact) pass
def build_dict_from_row_address(self, row): result = {} result['uid'] = row[0] result['username'] = row[1] result['lastName'] = row[2] result['firstName'] = row[3] result['address'] = Address().build_dict_from_row(row[4:]) return result
def convert_to_address_from(order_form, user_id): new_address = Address(address_name=order_form.address_name.data, address_1=order_form.address_1.data, address_2=order_form.address_2.data, city=order_form.city.data, state=order_form.state.data, zip_code=order_form.zip_code.data) return new_address
def getPostFromDistrict(self, loaibaiviet, tinh, huyen, minPrice, maxPrice, minArea): data = self.normalizeInputDataSearchPost(loaibaiviet, minPrice, maxPrice) tinh = Address.normalizeProvince(tinh) if tinh is None: return huyen = Address.normalizeDistrict(tinh, huyen) if huyen is None: return return [ Post().search(huyen + ", " + tinh, data["itemType"], data["minPrice"], data["maxPrice"], minArea, data["sort"], data["statusItem"], 1, data["usernameRenter"], data["pageNumber"]), { "stringSearch": huyen + ", " + tinh } ]
def select_all(): addresses = [] sql = "SELECT * FROM addresses" results = run_sql(sql) for row in results: address = Address(row["num"], row["street"], row["city"], row["postcode"], id) addresses.append(address) return addresses
def select(id): address = None sql = "SELECT * FROM addresses WHERE id = %s" values = [id] row = run_sql(sql, values)[0] if row is not None: address = Address(row["num"], row["street"], row["city"], row["postcode"], id) return address
def email_dups(): dao = Dao(stateful=True) # cities = Turf.get_city_names(dao) dups = Contact.get_email_dups(dao) dao.close() for dup in dups: dup['name'] = str(PersonName(dup)) dup['address'] = str(Address(dup)) return jsonify(dups)
def __init__(self, d=None): self.id = None self.name = None self.address = None self.birth_year = None self.gender = None self.voter_id = None self.precinct_id = None self.reg_date = None self.perm_abs = None self.status = None self.uocava = None self.ballot = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d)
def test_get_block(self): dao = Dao(db_file='c:/bench/bluestreets/data/26161.db', stateful=True) contact = Contact() contact.address = Address({'address': '3000 Newcastle Rd'}) contact.zipcode = '48105' block = Location.get_block(dao, contact) contact.zipcode = '' contact.city = 'ANN ARBOR' block = Location.get_block(dao, contact) dao.close()
def post(self): shop_data = ShopSchema().load(request.json) address_data = shop_data.pop("address_id") address = Address(**address_data) try: address.save() except: return {"message": ERROR_INSERTING_ADDRESS}, 500 shop = {"name": shop_data.get("name"), "address_id": address.id} shop = Shop(**shop) try: shop.save() except: return {"message": ERROR_INSERTING_SHOP}, 500 return {"id": str(shop.id)}, 201
def createPost(self): titlePost = str(request.get_json()["titlePost"]) contentPost = str(request.get_json()["contentPost"]) addressProvince = str(request.get_json()["addressProvince"]) addressDistrict = str(request.get_json()["addressDistrict"]) addressWard = str(request.get_json()["addressWard"]) addressDetail = str(request.get_json()["addressDetail"]) if not Address.checkAddress(addressProvince, addressDistrict, addressWard): time.sleep(10) return locationRelate = str(request.get_json()["locationRelate"]) itemType = str(request.get_json()["itemType"]) if itemType not in [ "phongtro", "nhanguyencan", "chungcumini", "chungcunguyencan" ]: time.sleep(10) return numOfRoom = int(request.get_json()["numOfRoom"]) priceItem = float(request.get_json()["priceItem"]) area = float(request.get_json()["area"]) statusItem = str(request.get_json()["statusItem"]) if statusItem not in ["chungchu", "khongchungchu"]: time.sleep(10) return bathroom = str(request.get_json()["bathroom"]) temp = bathroom.split(" ") if len(temp) != 2 or temp[0] not in [ "khepkin", "khongkhepkin" ] or temp[1] not in ["nonglanh", "khongnonglanh"]: time.sleep(10) return kitchen = str(request.get_json()["kitchen"]) if kitchen not in ["khubepchung", "khubeprieng", "khongnauan"]: time.sleep(10) return aircondition = int(request.get_json()["aircondition"]) if aircondition != 0 and aircondition != 1: time.sleep(10) return balcony = int(request.get_json()["balcony"]) if balcony != 0 and balcony != 1: time.sleep(10) return priceElectric = str(request.get_json()["priceElectric"]) priceWater = str(request.get_json()["priceWater"]) otherUtility = str(request.get_json()["otherUtility"]) postDuration = int(request.get_json()["postDuration"]) listImages = request.get_json()["listImages"] Post().create(titlePost, contentPost, addressProvince, addressDistrict, addressWard, addressDetail, locationRelate, itemType, numOfRoom, priceItem, area, statusItem, bathroom, kitchen, aircondition, balcony, priceElectric, priceWater, otherUtility, session["username"], session["type_account"], postDuration, listImages)
def run_test(): cities = Address.get_cities() f = open('voter_test.csv', 'r') rdr = csv.reader(f) submissions = [Submission.from_csv(row, cities, with_contact=False) for row in rdr] lookups = Voter.lookup(submissions) for lookup in lookups: print(str(lookup.name), str(lookup.address)) for match in lookup.matches: print(str(match), str(match.address)) print('\n')
def contact_matches(): contact = Contact(json.loads(request.form['params'])) dao = Dao(stateful=True) try: matches = contact.get_matches(dao) for match in matches: match['name'] = str(PersonName(match)) match['address'] = str(Address(match)) return jsonify(matches=matches) except Exception as ex: return jsonify(error=str(ex))
def __init__(self, d=None): self.id = None self.name = None self.birth_year = None self.gender = '' self.info = None self.address = None self.voter_id = None self.reg_date = '' self.bst_id = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d) self.info = ContactInfo(d)
def __init__(self, d=None): self.id = None self.name = None self.address = None self.birth_year = None self.gender = None self.voter_id = None self.reg_date = None self.perm_abs = None self.status = None self.uocava = None self.ballot = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d)
def other_create(user, params): amount = utils.decimal_two(params.get("amount", "")) location = utils.safe_id(params.get("location", "")) address = params.get("address", "") postcode = params.get("postcode", "") if not location or not amount: return {"error_code": 80002, "msg": "not enough parameters"} add = Address.select().where(Address.id == location).first() if not add or add and add.level != 3: return {"error_code": 20167, "msg": "location invalid"} if postcode and len(postcode) > 20 or len(address) > 100: return {"error_code": 20162, "msg": "too long"} if not amount: return {"error_code": 20163, "msg": "hourly invalid"} with database.atomic() as txn: try: user.reg_step = "other" user.status = "active" user.save() # 任务加分字断 columns = ["hourly", "location", "address"] profile = user.profile.first() profile.hourly = amount profile.location = location profile.address = address if postcode: profile.postcode = postcode columns.append("postcode") profile.save() queue.to_queue({"type": "user_completeness", "user_id": user.id, "columns": columns}) except: return {"error_code":20164, "msg":"save error"} return {"error_code": 0, "msg": "ok"}
class Contact(object): def __init__(self, d=None): self.id = None self.name = None self.birth_year = None self.gender = '' self.info = None self.address = None self.voter_id = None self.reg_date = '' self.bst_id = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d) self.info = ContactInfo(d) def __str__(self): return str(self.name) def serialize(self): return { 'name': self.name.serialize(), 'whole_name': str(self.name), 'birth_year': self.birth_year, 'gender': self.gender, 'contact': self.info.serialize(), 'address': self.address.serialize(), 'voter_id': self.voter_id, 'reg_date': self.reg_date, 'id': self.id, 'bst_id': self.bst_id } def get_values(self): return ( self.name.last, self.name.first, self.name.middle, self.name.suffix, self.name.nickname, self.name.last_meta, self.name.first_meta, self.name.nickname_meta, self.birth_year, self.gender, self.info.email, self.info.phone1, self.info.phone2, self.address.house_number, self.address.pre_direction, self.address.street_name, self.address.street_type, self.address.suf_direction, self.address.unit, self.address.metaphone, self.address.city, self.address.zipcode, self.address.precinct_id, self.voter_id, self.reg_date, self.bst_id ) def copy_voter(self, voter): if not self.name.nickname: self.name.nickname = self.name.first self.name.last = voter.name.last self.name.first = voter.name.first self.name.middle = voter.name.middle self.name.suffix = voter.name.suffix self.address.house_number = voter.address.house_number self.address.pre_direction = voter.address.pre_direction self.address.street_name = voter.address.street_name self.address.street_type = voter.address.street_type self.address.suf_direction = voter.address.suf_direction self.address.unit = voter.address.unit self.address.city = voter.address.city self.address.zipcode = voter.address.zipcode self.address.precinct_id = voter.address.precinct_id self.gender = voter.gender self.birth_year = voter.birth_year self.reg_date = voter.reg_date self.voter_id = voter.voter_id
class TestAddress(unittest.TestCase): """Tests the address class""" def setUp(self): self._address = Address() def test_street(self): """Tests setter and getter of street of an address""" street = "Mystreet 1" self._address.set_street(street) self.assertEqual(self._address.get_street(), street) def test_zip(self): """Tests setter and getter of zip of an address""" zip_number = "12345" self._address.set_zip(zip_number) self.assertEqual(self._address.get_zip(), zip_number) def test_city(self): """Tests setter and getter of city of an address""" city = City() self._address.set_city(city) self.assertIsInstance(self._address.get_city(), City) def test_string_casting(self): """Tests casting of an Address object""" street = "Mystreet 1" zip_number = "12345" city = City().set_name("City") self._address.set_street(street) self._address.set_zip(zip_number) self._address.set_city(city) expected_output = "%s\n%s %s" % ( self._address.get_street(), self._address.get_zip(), self._address.get_city() ) self.assertEqual(str(self._address), expected_output)
def setUp(self): self._address = Address()
class Voter(object): def __init__(self, d=None): self.id = None self.name = None self.address = None self.birth_year = None self.gender = None self.voter_id = None self.reg_date = None self.perm_abs = None self.status = None self.uocava = None self.ballot = None if d: for attr in self.__dict__: if attr in d: setattr(self, attr, d[attr]) self.name = PersonName(d) self.address = Address(d) def __str__(self): return str(self.name) def serialize(self): d = { 'voter_id': self.voter_id, 'name': self.name.serialize(), 'address': self.address.serialize(), 'precinct_id': self.address.precinct_id, 'birth_year': self.birth_year, 'gender': self.gender, 'reg_date': self.reg_date, 'perm_abs': self.perm_abs if self.perm_abs else 'N', 'status': self.status, 'uocava': self.uocava } if 'score' in self.__dict__: d['score'] = self.__dict__['score'] return d def get_values(self): return ( self.name.last, self.name.first, self.name.middle, self.name.suffix, self.name.last_meta, self.name.first_meta, self.birth_year, self.gender, self.address.house_number, self.address.pre_direction, self.address.street_name, self.address.street_type, self.address.suf_direction, self.address.unit, self.address.metaphone, self.address.city, self.address.zipcode, self.address.precinct_id, self.voter_id, self.reg_date, self.perm_abs, self.status, self.uocava )
def user_profile_update(user, params): if len(params) == 0: return {"error_code": 0, "msg": "ok"} email = params.get("email") name = params.get("name") location = utils.safe_id(params.get('location')) address = params.get("address") postcode = params.get("postcode") available = params.get("available") workload = params.get("workload") title = params.get("title") overview = params.get("overview") hourly = params.get("hourly") skills = params.get("skills") english = params.get("english") other = params.get("other", "").strip() level = params.get("level") # 更新分值字断名称 columns = list() profile = user.profile.first() if email is not None: if not validate.is_email(email): return {"error_code": 202710, "msg": "email invalid"} u = User.select().where(User.email == email).first() if u and u.id != user.id: return {"error_code": 202711, "msg": "email is exists"} user.email = email user.save() columns.append("email") if level is not None: if level not in ("entry", "middle", "expert"): return {"error_code": 202712, "msg": "level invalid"} if profile.level != level: profile.level = level columns.append("level") if name is not None: if name.strip() != profile.name: if profile.id_number: return {"error_code": 20271, "msg": "already verify user, not allow modify name"} profile.name = name if location: add = Address.select().where(Address.id == location).first() if not add or add and add.level != 3: return {"error_code": 20272, "msg": "location invalid"} profile.location = location columns.append("location") if address is not None: if len(address) > 100: return {"error_code": 20273, "msg": "address too long"} profile.address = address columns.append("address") if postcode is not None: if len(postcode) > 20: return {"error_code": 20274, "msg": "postcode too long"} profile.postcode = postcode columns.append("postcode") if available is not None: if available == "true": profile.available = True elif available == "false": profile.available = False if workload is not None: if not (workload.isdigit() and 1 <= int(workload) <= 3): return {"error_code": 202713, "msg": "workload invalid"} profile.workload = workload columns.append("workload") if title is not None: if len(title) > 29: return {"error_code": 20275, "msg": "title too long"} profile.title = title columns.append("title") if overview is not None: if len(overview) > 1024 * 1024 * 4: return {"error_code": 20276, "msg": "overview too long"} profile.overview = overview columns.append("overview") if hourly is not None: try: hourly = float(hourly) except: return {"error_code": 20277, "msg": "hourly invalid"} profile.hourly = hourly columns.append("hourly") if english is not None: if english not in ("1", "2", "3", "4"): return {"error_code": 20278, "msg": "english level invalid"} profile.english = english columns.append("english") other_lan = None if other: try: other_lan = utils.loads(other) for y in other_lan: if y not in all_languages or str(other_lan[y]) not in ("1", "2", "3", "4"): other_lan.pop(y) except: return {"error_code":20128, "msg":"other language invalid"} if other_lan != None: _user_lang = UserLanguage.select().where(UserLanguage.user==user) for x in _user_lang: if x.name not in other_lan: x.delete_instance() else: if x.level != other_lan[x.name]: x.level = other_lan[x.name] x.save() other_lan.pop(x.name) else: other_lan.pop(x.name) for y in other_lan: UserLanguage.create(user=user, name=y, level=other_lan[y]) columns.append("other_language") if skills is not None: s = None try: s = [x for x in skills.split(",") if x in all_skills] except: return {"error_code": 20279, "msg": "skills invalid"} if s: profile.skills = utils.dumps(s) columns.append("skills") profile.save() queue.to_queue({"type": "user_completeness", "user_id": user.id, "columns": columns}) return {"error_code": 0, "msg": "ok"}