def vote(): flask.request.environ['CONTENT_TYPE'] = 'application/json' try: if flask.request.method == 'POST': # Save vote in database # Parse request first requestStr = flask.request.data panchromious.app.logger.info('Received request: %s', requestStr) voteObj = flask.json.loads(requestStr) panchromious.app.logger.info('Decoded request: %s', voteObj) colorRed = voteObj['color']['red'] colorGreen = voteObj['color']['green'] colorBlue = voteObj['color']['blue'] name = voteObj['value'] # Verify that R,G,B components are in valid range if not utils.are_valid_rgb_values([colorRed, colorGreen, colorBlue]) or not name: panchromious.app.logger.error('Incorrect request: color: [%d, %d, %d], name: %s', colorRed, colorGreen, colorBlue, name) return utils.error_response('Incorrect request') else: model.save_vote(colorRed, colorGreen, colorBlue, name) return utils.generate_response(201, utils.generate_vote()) else: # GET # Generate new vote return utils.generate_response(200, utils.generate_vote()) except: panchromious.app.logger.info('Error: %s', sys.exc_info()[2]) return utils.generate_response(500, {'status': 'error'})
def delete_todo(todo_id): todo = Todo.query.filter_by(id=todo_id).first() if not todo: return generate_response(404, 'Task not found.') db.session.delete(todo) db.session.commit() return generate_response(200, 'Task deleted.')
def add_todo(): post_data = request.get_json() if not post_data: return generate_response(400, 'Invalid payload.') task = post_data.get('task') todo = Todo(task=task) db.session.add(todo) db.session.commit() return generate_response(201, 'Task added.', todo_serializer(todo))
def update_todo(todo_id): todo = Todo.query.filter_by(id=todo_id).first() if not todo: return generate_response(404, 'Task not found.') post_data = request.get_json() if not post_data: return generate_response(400, 'Invalid payload.') todo.done = post_data.get('done') db.session.commit() return generate_response(200, 'Task updated.', todo_serializer(todo))
def buscar_clima(): service = ClimaService() args = request.args try: data = service.get(args) serializer = ClimaSerializer() model = Clima(data) retorno = serializer.dump(model) service.add_history() return generate_response(200, '', 'tempo', retorno) except HTTPError as he: return generate_response(200, 'Dados não encontrados com o termo digitado')
def get_color(red, green, blue): flask.request.environ['CONTENT_TYPE'] = 'application/json' try: if not utils.are_valid_rgb_values([red, green, blue]): panchromious.app.logger.error('Incorrect color values: [%d, %d, %d]', red, green, blue) return utils.error_response('Color values should be in <0;255>') else: # Response panchromious.app.logger.error((red, green, blue)) return utils.generate_response(200, model.get_color(red, green, blue)) except: panchromious.app.logger.info('Error: %s', sys.exc_info()[2]) return utils.generate_response(500, {'status': 'error'})
def post(self): """ Insert a new item, the item_uuid identifier is forwarded from the one generated from the database """ request_data = request.get_json(force=True) errors = Item.validate_input(request_data) if errors: return errors, client.BAD_REQUEST data = request_data['data']['attributes'] if int(data['availability']) < 0: return None, client.BAD_REQUEST item = Item.create( uuid=uuid.uuid4(), name=data['name'], price=float(data['price']), description=data['description'], availability=int(data['availability']), category=data['category'], ) return generate_response(item.json(), client.CREATED)
def test_generate_response_with_valid_header_and_invalid_extension(self): env = create_environ(headers={'Accept': 'application/json'}) req = Request(env) resp = utils.generate_response(request=req, data=None, \ format='foo') self.assertEqual(resp.status_code, 406) self.assertEqual(resp.status, '406 NOT ACCEPTABLE')
def get(self): query = request.args.get('query') limit = int(request.args.get('limit', -1)) min_limit, max_limit = 0, 100 limit_in_range = limit > min_limit and limit <= max_limit if query is not None and limit_in_range: matches = Item.search(query, Item.select(), limit) return generate_response(Item.json_list(matches), client.OK) def fmt_error(msg): return {'detail': msg} errors = {"errors": []} if not query: errors['errors'].append(fmt_error('Missing query.')) if not limit_in_range: msg = 'Limit out of range. must be between {} and {}. Requested: {}' errors['errors'].append( fmt_error(msg.format(min_limit, max_limit, limit))) return errors, client.BAD_REQUEST
def patch(self): """Edit the current logged user""" request_data = request.get_json(force=True) errors = User.validate_input(request_data, partial=True) if errors: return errors, BAD_REQUEST user = auth.current_user data = request_data['data']['attributes'] first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') if first_name: user.first_name = first_name if last_name: user.last_name = last_name if email: user.email = email user.save() return generate_response(user.json(), OK)
def post(self): """ Add an user to the database.""" data = request.get_json(force=True) errors = User.validate_input(data) if errors: return errors, BAD_REQUEST # Extract the user attributes to check and generate the User row data = data['data']['attributes'] # If email is present in the database return a BAD_REQUEST response. if User.exists(data['email']): msg = {'message': 'email already present.'} return msg, CONFLICT new_user = User.create( uuid=uuid.uuid4(), first_name=data['first_name'], last_name=data['last_name'], email=data['email'], password=User.hash_password(data['password']) ) notify_new_user(first_name=new_user.first_name, last_name=new_user.last_name) # If everything went OK return the newly created user and CREATED code # TODO: Handle json() return value (data, errors) and handle errors not # empty return generate_response(new_user.json(), CREATED)
def test_generate_response_with_only_accept_header(self): env = create_environ(headers={'Accept': 'application/json'}) req = Request(env) resp = utils.generate_response(request=req) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.status, '200 OK') self.assertEqual(resp.content_type, 'application/json')
def get(self, item_uuid): """Retrieve the item specified by item_uuid""" try: item = Item.get(Item.uuid == item_uuid) return generate_response(item.json(), client.OK) except Item.DoesNotExist: return None, client.NOT_FOUND
def test_generate_response_with_only_extension(self): env = create_environ() req = Request(env) resp = utils.generate_response(request=req, data=None, \ format='json') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.status, '200 OK') self.assertEqual(resp.content_type, 'application/json')
def test_generate_response_with_invalid_header_and_valid_extension(self): env = create_environ(headers={'Accept': 'application/foo'}) req = Request(env) resp = utils.generate_response(request=req, data=None, \ format='json') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.status, '200 OK') self.assertEqual(resp.content_type, 'application/json')
def get(self, order_uuid): """ Get a specific order, including all the related Item(s).""" try: order = Order.get(Order.uuid == order_uuid) except Order.DoesNotExist: return None, NOT_FOUND return generate_response(order.json(), OK)
def person_list(): """ Get a list of persons. """ results = Person.select().order_by(Person.id.desc()).execute() response = generate_response( {'data': [model_to_dict(result) for result in results]}, 200) return response
def get(self, id=None, format=None): # TODO: add case-insensitive lookup if id: data = self._get_trial(id) else: data = self._get_trials(limit=request.args.get('limit', 50),\ skip=request.args.get('offset', 0)) return generate_response(request, data, format=format)
def get(self, item_uuid): """Retrieve every picture of an item""" pictures = Picture.select().join(Item).where(Item.uuid == item_uuid) if pictures: data = Picture.json_list(pictures) return generate_response(data, client.OK) return None, client.NOT_FOUND
def pet_list_null_owner(): """ Get a list of pets from null owner. """ results = Pet.select().where(Pet.owner.is_null()).order_by( Pet.id.desc()).execute() response = generate_response( {'data': [model_to_dict(result) for result in results]}, 200) return response
def get(self, address_uuid): try: addr = Address.get( Address.user == auth.current_user, Address.uuid == address_uuid ) return generate_response(addr.json(), OK) except Address.DoesNotExist: return None, NOT_FOUND
def patch(self, order_uuid): """ Modify a specific order. """ res = request.get_json(force=True) errors = Order.validate_input(res, partial=True) if errors: return errors, BAD_REQUEST data = res['data']['relationships'] req_items = data.get('items', {}) req_address = data.get('delivery_address') with database.atomic(): try: order = Order.get(uuid=str(order_uuid)) except Order.DoesNotExist: abort(NOT_FOUND) address = None if req_address: try: address = Address.get( Address.uuid == req_address['data']['id']) except Address.DoesNotExist: abort(BAD_REQUEST) order.delivery_address = address # get the user from the flask.g global object registered inside the # auth.py::verify() function, called by @auth.login_required decorator # and match it against the found user. # This is to prevent uses from modify other users' order. if auth.current_user != order.user and auth.current_user.admin is False: return ({ 'message': "You can't delete another user's order" }, UNAUTHORIZED) # Generate the dict of {<Item>: <int:quantity>} to call Order.update_items items_uuids = [e['id'] for e in req_items.get('data', [])] items = list(Item.select().where(Item.uuid << items_uuids)) if len(items) != len(items_uuids): abort(BAD_REQUEST) items_to_add = { item: req_item['quantity'] for item in items for req_item in req_items.get('data', []) if str(item.uuid) == req_item['id'] } try: order.update_items(items_to_add, new_address=address) except InsufficientAvailabilityException: abort(BAD_REQUEST) return generate_response(order.json(), OK)
def person(person_id): """ Get an existing person. """ try: result = Person.get_or_none(Person.id == person_id) if result is None: raise NotFoundException('Person not found') response = generate_response(model_to_dict(result), 200) except Exception as e: app.logger.error(e) response = generate_error_response(e) return response
def historico_busca(): args = request.args if 'city' in args: historicos = Historico.query.filter(tipo_busca='city').all() elif 'code' in args: historicos = Historico.query.filter(tipo_busca='code').all() elif 'zipcode' in args: historicos = Historico.query.filter(tipo_busca='zipcode').all() elif 'coord' in args: historicos = Historico.query.filter(tipo_busca='coord').all() else: historicos = Historico.query.all() serializer = HistoricoSerializer(many=True) retorno = serializer.dump(historicos) return generate_response(200, '', 'historicos', retorno)
def update_person(person_id): """ Update a person and marries partners if eligible. """ try: result = Person.get_or_none(Person.id == person_id) if result is None: raise NotFoundException('Person not found') data = request.get_json(force=True) first_name = data.get('first_name') if first_name is not None: result.first_name = first_name last_name = data.get('last_name') if last_name is not None: result.last_name = last_name partner_id = data.get('partner_id') if partner_id is not None: partner = result.partner if partner is None: partner = Person.get_or_none(Person.id == partner_id) if partner is None: raise NotFoundException('Partner not found') if partner.partner is not None: raise ConflictException('Partner already married') if partner_id != partner.id: raise InvalidRequestException( 'Partner does not match partner_id') if partner is not None: partner.partner = result partner.save() result.partner = partner result.save() response = generate_response(model_to_dict(result), 200) except Exception as e: app.logger.error(e) response = generate_error_response(e) return response
def pet_list(person_id): """ Get a list of pets from an existing owner. """ try: owner = Person.get_or_none(Person.id == person_id) if owner is None: raise NotFoundException('Owner not found') results = Pet.select().where(Pet.owner == person_id).order_by( Pet.id.desc()).execute() response = generate_response( {'data': [model_to_dict(result) for result in results]}, 200) except Exception as e: app.logger.error(e) response = generate_error_response(e) return response
def post(self): res = request.get_json(force=True) errors = Address.validate_input(res) if errors: return errors, BAD_REQUEST data = res['data']['attributes'] addr = Address.create( uuid=uuid.uuid4(), user=auth.current_user, country=data['country'], city=data['city'], post_code=data['post_code'], address=data['address'], phone=data['phone']) return generate_response(addr.json(), CREATED)
def post(self): request_data = request.get_json(force=True) if 'email' not in request_data or 'password' not in request_data: abort(client.BAD_REQUEST) email = request_data['email'] password = request_data['password'] try: user = User.get(User.email == email) except User.DoesNotExist: abort(client.BAD_REQUEST) if not user.verify_password(password): abort(client.UNAUTHORIZED) login_user(user) return generate_response({}, client.OK)
def patch(self, address_uuid): try: obj = Address.get(Address.user == auth.current_user, Address.uuid == address_uuid) except Address.DoesNotExist: return None, NOT_FOUND res = request.get_json(force=True) errors = Address.validate_input(res) if errors: return errors, BAD_REQUEST data = res['data']['attributes'] country = data.get('country') city = data.get('city') post_code = data.get('post_code') address = data.get('address') phone = data.get('phone') if country and country != obj.country: obj.country = country if city and city != obj.city: obj.city = city if post_code and post_code != obj.post_code: obj.post_code = post_code if address and address != obj.address: obj.address = address if phone and phone != obj.phone: obj.phone = phone obj.save() return generate_response(obj.json(), OK)
def create_person(): """ Create a person and marries partners if eligible. """ try: data = request.get_json(force=True) first_name = data.get('first_name') last_name = data.get('last_name') partner_id = data.get('partner_id') partner = None if first_name is None: raise InvalidRequestException('First name is required') if last_name is None: raise InvalidRequestException('Last name is required') if partner_id is not None: partner = Person.get_or_none(Person.id == partner_id) if partner is None: raise NotFoundException('Partner not found') if partner.partner is not None: raise ConflictException('Partner already married') result = Person(first_name=first_name, last_name=last_name, partner=partner) result.save() if partner is not None: partner.partner = result partner.save() response = generate_response(model_to_dict(result), 201) except Exception as e: app.logger.error(e) response = generate_error_response(e) return response
def patch(self, item_uuid): """Edit the item specified by item_uuid""" try: obj = Item.get(Item.uuid == item_uuid) except Item.DoesNotExist: return None, client.NOT_FOUND request_data = request.get_json(force=True) errors = Item.validate_input(request_data, partial=True) if errors: return errors, client.BAD_REQUEST data = request_data['data']['attributes'] name = data.get('name') price = data.get('price') description = data.get('description') availability = data.get('availability') category = data.get('category') if name: obj.name = name if price: obj.price = price if description: obj.description = description if availability: obj.availability = availability if category: obj.category = category obj.save() return generate_response(obj.json(), client.OK)
def create_pet(person_id): """ Create a pet for an existing owner. """ try: owner = Person.get_or_none(Person.id == person_id) if owner is None: raise NotFoundException('Owner not found') data = request.get_json(force=True) name = data.get('name') if name is None: raise InvalidRequestException('Name is required') result = Pet(name=name, owner=owner) result.save() response = generate_response(model_to_dict(result), 201) except Exception as e: app.logger.error(e) response = generate_error_response(e) return response
def post(self): user = auth.current_user res = request.get_json(force=True) errors = Favorite.validate_input(res) if errors: return errors, BAD_REQUEST data = res['data']['attributes'] try: item = Item.get(Item.uuid == data['item_uuid']) except Item.DoesNotExist: return {"message": "Item {} doesn't exist as Favorite.".format( data['item_uuid'])}, NOT_FOUND has_already = Item.is_favorite(user, item) if has_already: return {"message": "Item {} was already been inserted as Favorite.".format( data['item_uuid'])}, OK favorite = user.add_favorite(item) return generate_response(favorite.json(), CREATED)
def get(self): return generate_response(auth.current_user.json(), OK)
def get(self): if not auth.current_user.admin: return ({'message': "You can't get the list users."}, UNAUTHORIZED) data = User.json_list(User.select()) return generate_response(data, OK)
def test_generate_response_with_only_bad_accept_header(self): env = create_environ(headers={'Accept': 'applictation/blah'}) req = Request(env) resp = utils.generate_response(request=req) self.assertEqual(resp.status_code, 406) self.assertEqual(resp.status, '406 NOT ACCEPTABLE')
def test_generate_response_no_header_no_extension(self): env = create_environ() req = Request(env) resp = utils.generate_response(request=req) self.assertEqual(resp.status_code, 406) self.assertEqual(resp.status, '406 NOT ACCEPTABLE')
def handle_405(error): return utils.generate_response(request, {'error': 'Method not allowed'})
def post(self): logout_user() return generate_response({}, client.OK)
def get(self): """Retrieve every item""" data = Item.json_list(Item.select()) return generate_response(data, client.OK)