def address_delete(): id = request.args["id"] if id: Address.delete_address(id=id) return Success(msg="删除成功") else: return ParameterException(msg="请传入地址id")
def save_address(address_id): ''' Creates or modifies existing address ''' payload = request.get_json() if not payload: abort(Response('No data was provided', status=400)) if payload.get('zip'): try: float(payload['zip']) except: abort(Response('Not number', status=400)) address = None if address_id is None: address = Address() address.when_created = datetime.now() db.session.add(address) else: address = Address.query.get(address_id) if not address: abort(Response(f'No address <{address_id}> was found', status=400)) for key, value in payload.items(): if getattr(address, key) != value: setattr(address, key, value) address.when_changed = datetime.now() db.session.commit() return jsonify(address.to_dict())
def amend(): data = eval(str(request.data, encoding='utf-8')) form = AddressAmend(ImmutableMultiDict(data)) if form.validate(): Address.amend_default_address(form) return Success(msg="更改地址成功") else: return ParameterException(msg=form.errors)
def address_list(): userId = request.args["userId"] if userId: address = Address.address_list(userId=userId) return Result(data=address) else: return ParameterException(msg="请传入用户id")
def delete(self, address_id): # Delete address success = Address.delete_by_id(address_id) if not success: abort(404) return {'result': True}
def post(self, user_id): # Get arguments args = self.parser.parse_args() # Validate user, address and cleaner ids if User.get_by_id(user_id) is None: abort(404, 'User not found') if Address.get_by_id(args['address_id']) is None: abort(404, 'Address not found') if Cleaner.get_by_id(args['cleaner_id']) is None: abort(404, 'Cleaner not found') # Create new order order = Order(user_id=user_id, address_id=args['address_id'], cleaner_id=args['cleaner_id'], date=args['date'], start_time=args['start_time'], end_time=args['end_time'], rooms=args['rooms'], special_rooms=args['special_rooms'], extra_services=args['extra_services'], reference=args['reference'], transaction=args['transaction'], price=args['price']) # Persist and return order success = order.persist() if not success: abort(400, 'Parameters incorrect') return order, 201
def buildLawn(lawn_dict): lawn_name = lawn_measure = address1 = address2 = city = state = zip = country = '' lawn_area = 0 if 'name' in lawn_dict: lawn_name = lawn_dict['name'] if 'total_area' in lawn_dict: lawn_area = lawn_dict['total_area'] if 'unit_of_measure' in lawn_dict: lawn_measure = lawn_dict['unit_of_measure'] if 'address1' in lawn_dict['address']: address1 = lawn_dict['address']['address1'] if 'address2' in lawn_dict['address']: address2 = lawn_dict['address']['address2'] if 'city' in lawn_dict['address']: city = lawn_dict['address']['city'] if 'state' in lawn_dict['address']: state = lawn_dict['address']['state'] if 'zip' in lawn_dict['address']: zip = lawn_dict['address']['zip'] if 'country' in lawn_dict['address']: country = lawn_dict['address']['country'] address = Address(address1, address2, city, state, zip, country) lawn = Lawn(lawn_name, address, lawn_area, lawn_measure) return lawn
def find_address_by_zip(self, request: Request): zip_code = get_param_or_400(request.query_params, "zip", str) if len(zip_code) != 8: raise ValueError(_("Zip code length should have exactly 8")) result_dict = { "city": {"id": None, "description": None}, "zip": None, "neighborhood": {"id": None, "description": None}, "state": {"id": None, "description": None, "initials": None}, "address": None, } try: address = Address.get_by_zip(zip_code) except Address.DoesNotExist: address = None if address: result_dict["city"]["id"] = address.neighborhood.city.id result_dict["city"]["description"] = address.neighborhood.city.description result_dict["zip"] = address.zip_code result_dict["neighborhood"]["id"] = address.neighborhood.id result_dict["neighborhood"][ "description" ] = address.neighborhood.description result_dict["state"]["id"] = address.neighborhood.city.state.id result_dict["state"][ "description" ] = address.neighborhood.city.state.description result_dict["state"]["initials"] = address.neighborhood.city.state.initials result_dict["address"] = address.description return Response(data=result_dict)
def test_get_address(self): self.try_add_entities([ Address(id=123, name='Address_1', zip=11111, address_1='address01', address_2='address02') ]) res = self.try_user_operation( lambda: self.client.get('/api/v1/admin/addresses')) self.assertEqual(len(res.json), 1)
def test_get_address(self): self.try_add_entities([ Address(id=2) ]) self.try_admin_operation( lambda: self.client.get('/admin/addresses/') )
def get(self, address_id): # Get address by id address = Address.get_by_id(address_id) if address is None: abort(404) # Return address return address
def mutate(cls, _, info, geo_api_data, company_id, alias=None): company_known_address = CompanyKnownAddress( alias=alias, address=Address.get_or_create(geo_api_data), company_id=company_id, ) db.session.add(company_known_address) db.session.commit() return company_known_address
def post(self, user_id): # Validate user if User.get_by_id(user_id) is None: abort(404, 'User not found') # Create new address args = self.parser.parse_args() address = Address(user_id=user_id, street=args['street'], house_number=args['house_number'], city=args['city'], post_code=args['post_code'], flat_number=args['flat_number'], country=args['country'], neighbourhood=args['neighbourhood']) # Persist and return address address.persist() return address, 201
def test_delete_address(self): gen_id = int(datetime.now().timestamp()) self.try_add_entities([ Address(id=gen_id, name='Address_1', zip='11111', address_1='address01', address_2='address02') ]) res = self.try_admin_operation( lambda: self.client.delete(f'/api/v1/admin/addresses/{gen_id}') ) self.assertEqual(res.status_code, 200) address = Address.query.get(gen_id) self.assertEqual(address, None)
def post(self): ''' Create an address ''' arguments = request.get_json(force=True) district = arguments.get('district').strip() postal = arguments.get('postal').strip() or None country = arguments.get('country').strip() or None address_line_1 = arguments.get('address1').strip() or None address_line_2 = arguments.get('address1').strip() or None if not address_line_1: return abort(400, 'Address cannot be empty!') try: address = Address( district=district, postal_code=postal, country=country, address_line_1=address_line_1, address_line_2=address_line_2 ) if address.save_address(): return {'message': 'Address created successfully!'}, 201 return abort(409, message='Address already exists!') except Exception as e: abort(400, message='Failed to create new address -> {}'.format(e))
def test_save_address(self): gen_id = int(datetime.now().timestamp()) self.try_add_entities([ Address(id=gen_id, name='Address_1', zip='11111', address_1='address01', address_2='address02') ]) res = self.try_admin_operation( lambda: self.client.post(f'/api/v1/admin/addresses/{gen_id}', json={'zip': '22222'}) ) self.assertEqual(res.status_code, 200) address = Address.query.get(gen_id) self.assertEqual(address.zip, '22222') res = self.client.post(f'/api/v1/admin/addresses/{gen_id}', json={'zip': '22222@'}) self.assertEqual(res.status_code, 400)
def test_create_purchase_order(self): gen_id = f'{__name__}-{int(datetime.now().timestamp())}' gen_int_id = int(datetime.now().timestamp()) self.try_add_entities([ Order(id=gen_id, user=self.user, status=OrderStatus.can_be_paid), Subcustomer(id=gen_int_id), Subcustomer(id=gen_int_id + 1), Suborder(id=gen_id, order_id=gen_id, subcustomer_id=gen_int_id), Suborder(id=gen_id + '1', order_id=gen_id, subcustomer_id=gen_int_id + 1), OrderProduct(suborder_id=gen_id, product_id='0000'), OrderProduct(suborder_id=gen_id + '1', product_id='0000'), Address(id=gen_int_id, zip='00000'), Company(id=gen_int_id, address_id=gen_int_id) ])
def build_from_db_record(record): new_user = User(record) new_user.credit_card = CreditCard({ 'expire_year': record['credit_card']['expire']['year'], 'expire_month': record['credit_card']['expire']['month'], 'number': record['credit_card']['number'] }) new_user.address = Address({ 'country': record['address']['country'], 'zip': record['address']['zip'], 'street': record['address']['street'], 'num': record['address']['num'], }) return new_user
def setUp(self): super().setUp() db.create_all() admin_role = Role(id=10, name='admin') self.try_add_entities([ User(id=0, username='******', email='*****@*****.**', password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True, roles=[admin_role]), User(id=10, username='******', email='*****@*****.**', password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True), User(id=20, username='******', email='*****@*****.**', password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True), admin_role, Address() ])
def put(self, address_id): # Get address by id address = Address.get_by_id(address_id) if address is None: abort(404) # Update address fields args = self.parser.parse_args() address.street = assign(args['street'], address.street) address.house_number = assign(args['house_number'], address.house_number) address.flat_number = assign(args['flat_number'], address.flat_number) address.post_code = assign(args['post_code'], address.post_code) address.city = assign(args['city'], address.city) address.country = assign(args['country'], address.country) address.neighbourhood = assign(args['neighbourhood'], address.neighbourhood) # Persist changes and return address address.persist() return address
def test_create_payment_transaction(self): gen_id = f'{__name__}-{int(datetime.now().timestamp())}' gen_id_int = datetime.now().microsecond self.try_add_entities([ Order(id=gen_id, user=self.user), Currency(code='USD', name='US Dollar', rate=1), Address(id=gen_id_int), Company(id=gen_id_int, address_id=gen_id_int), # PaymentMethod(id=gen_id_int, payee_id=gen_id_int), Payment(id=gen_id_int, user=self.user, currency_code='USD', amount_sent_krw=2600, amount_received_krw=2600) ]) res = self.try_admin_operation( lambda: self.client.post(f'/api/v1/admin/payment/{gen_id_int}', json={'status': 'approved'})) self.assertEqual(res.status_code, 200) transaction = Transaction.query.first() self.assertEqual(transaction.amount, 2600) self.assertEqual(self.user.balance, 2600)
def createProvider(): providerForm = ProviderForm() contactForm = ContactForm() addressForm = AddressForm() if providerForm.validate_on_submit(): address = Address(addressForm.street.data, addressForm.number.data, addressForm.complement.data, addressForm.district.data, addressForm.city.data, addressForm.state.data, addressForm.country.data, addressForm.postal_code.data) db.session.add(address) db.session.commit() provider = Provider(providerForm.trading_name.data, providerForm.company_name.data, providerForm.document_number.data, providerForm.cnae.data, providerForm.ie.data, providerForm.im.data, address.id) db.session.add(provider) db.session.commit() contact = Contact(contactForm.phone.data, contactForm.email.data, contactForm.employee_name.data, contactForm.employee_department.data, provider.id) db.session.add(contact) db.session.commit() flash('Fornecedor cadastrado com sucesso!', 'success') return redirect(url_for('indexProvider')) return render_template('provider/form.html', providerForm=providerForm, contactForm=contactForm, addressForm=addressForm)
def test_create_payment(self): gen_id = f'{__name__}-{int(datetime.now().timestamp())}' gen_id_int = datetime.now().microsecond self.try_add_entities([ Order(id=gen_id, user=self.user), Currency(code='USD', name='US Dollar', rate=1), Address(id=gen_id_int), Company(id=gen_id_int, address_id=gen_id_int), PaymentMethod(id=gen_id_int, payee_id=gen_id_int) ]) res = self.try_user_operation( lambda: self.client.post('/api/v1/payment', json={ 'orders': [gen_id], 'amount_sent_original': 100, 'currency_code': 'USD', 'payment_method': { 'id': gen_id_int } })) self.assertEqual(Payment.query.count(), 1) transaction = Payment.query.first() self.assertEqual(transaction.amount_sent_krw, 100)
def register_barber_shop(): try: session = current_app.db.session request_data = request.get_json() error_list = [] if request_data: if not Barber_shop.query.filter_by( name=request_data["name"]).first(): name = request_data["name"] else: error_list.append("name") if not Barber_shop.query.filter_by( phone_number=request_data["phone_number"]).first(): phone_number = request_data["phone_number"] else: error_list.append("phone_number") if not Barber_shop.query.filter_by( cnpj=request_data["cnpj"]).first(): cnpj = request_data["cnpj"] else: error_list.append("cnpj") if not Barber_shop.query.filter_by( email=request_data["email"]).first(): email = request_data["email"] else: error_list.append("email") if error_list: raise NameError(error_list) barber_shop = Barber_shop( name=name, phone_number=phone_number, cnpj=cnpj, email=email, user_type="barber_shop", ) barber_shop.password = request_data["password"] address = Address( state=request_data["address"]["state"], city=request_data["address"]["city"], street_name=request_data["address"]["street_name"], building_number=request_data["address"]["building_number"], zip_code=request_data["address"]["zip_code"], ) session.add(barber_shop) session.add(address) session.commit() address.barber_shop_id = barber_shop.id session.commit() barber_shop_serialized = BarberSchema().dump(barber_shop) address_serializer = AddressSchema().dump(address) barber_shop_serialized["address"] = address_serializer return {"data": barber_shop_serialized}, HTTPStatus.CREATED else: return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST except IntegrityError as e: error_origin = e.orig.diag.message_detail error = re.findall("\((.*?)\)", error_origin) return {"msg": f"{error[0].upper()} already registered"}, HTTPStatus.OK except KeyError: return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST except NameError as e: unique = e.args[0] errors = "" for error in unique: errors = errors + f"{error}, " return {"msg": f"{errors}already registered"}, HTTPStatus.BAD_REQUEST except DataError: return {"msg": "Verify BODY content"}, HTTPStatus.BAD_REQUEST
def create_address(): '''新增「配送信息」''' address_info = CreateOrUpdateAddressValidator().get_data(as_dict=True) Address.create(user_id=g.user.id, **address_info) return Success(error_code=1)
def get_address(id): '''查询「配送信息」''' address = Address.get_or_404(id=id, error_code=6001, msg='配送地址不存在') return Success(address)
def __init__(self, name, address = Address(), total_area = 0, unit_of_measurement = ''): self.id = '' self.address = address self.name = name self.total_area = total_area self.unit_of_measurement = unit_of_measurement
def deserialize(lawn_dict): lawn = Lawn(lawn_dict['name'], Address.deserialize(lawn_dict['address']), lawn_dict['total_area'], lawn_dict['unit_of_measure']) lawn.id = str(lawn_dict['_id']) return lawn
from app.models.lawn import Lawn from app.models.address import Address ADDRESSES = [ Address('123 Main St.', '', 'Chicago', 'IL', '12345', 'USA'), Address('555 Fifth St.', 'Apt 2', 'New York', 'NY', '12345', 'USA'), Address('20445 Royal Road', '', 'LONDON', 'WIP', '6HQ', 'ENGLAND'), Address('4545 Continental Cir', '', '', 'St Paul', '06570', 'France') ] LAWNS = [ Lawn('Home', ADDRESSES[0], 5000, 'sq. ft'), Lawn('Parents', ADDRESSES[1], 1200, 'sq. ft'), Lawn('Summer Home', ADDRESSES[2], 500, 'sq m'), Lawn('Somewhere else', ADDRESSES[3], 1000, 'sq m') ]
def delete_address(id, user_id): address = Address.get_or_404(id=id, user_id=user_id) address.delete()