def handle_amenity_for_place(place_id, amenity_id): '''Add the amenity with `amenity_id` to the place with `place_id` with a POST request. Delete the amenity with the id of `amenity_id` with a DELETE request. Keyword arguments: place_id -- The id of the place. amenity_id -- The id of the amenity. ''' try: Amenity.select().where(Amenity.id == amenity_id).get() except Amenity.DoesNotExist: return jsonify(msg="Amenity does not exist."), 404 try: Place.select().where(Place.id == place_id).get() except Place.DoesNotExist: return jsonify(msg="Place does not exist."), 404 if request.method == 'POST': '''Save the connection in the ReviewPlace table.''' PlaceAmenities().create(place=place_id, amenity=amenity_id) return jsonify(msg="Amenity added to place successfully."), 201 elif request.method == 'DELETE': (PlaceAmenities .delete() .where((PlaceAmenities.place == place_id) & (PlaceAmenities.amenity == amenity_id)) .execute()) Amenity.delete().where(Amenity.id == amenity_id).execute() return jsonify(msg="Amenity deleted successfully."), 200
def handle_amenity_for_place(place_id, amenity_id): '''Add the amenity with `amenity_id` to the place with `place_id` with a POST request. Delete the amenity with the id of `amenity_id` with a DELETE request. Keyword arguments: place_id -- The id of the place. amenity_id -- The id of the amenity. ''' try: Amenity.select().where(Amenity.id == amenity_id).get() except Amenity.DoesNotExist: return jsonify(msg="Amenity does not exist."), 404 try: Place.select().where(Place.id == place_id).get() except Place.DoesNotExist: return jsonify(msg="Place does not exist."), 404 if request.method == 'POST': '''Save the connection in the ReviewPlace table.''' PlaceAmenities().create(place=place_id, amenity=amenity_id) return jsonify(msg="Amenity added to place successfully."), 201 elif request.method == 'DELETE': (PlaceAmenities.delete().where((PlaceAmenities.place == place_id) & ( PlaceAmenities.amenity == amenity_id)).execute()) Amenity.delete().where(Amenity.id == amenity_id).execute() return jsonify(msg="Amenity deleted successfully."), 200
def amenities_in_places(place_id): if request.method == 'GET': amenities_list = [] amenities = Amenity.select().join(Place).where(Place.id == place_id) for amenity in amenities: amenities_list.append(amenity.to_hash()) return jsonify(amenities_list)
def amenities(): """Handle GET and POST requests to /amenities route. Return a list of all amenities in database in the case of a GET request. Create a new amenity record in the database in the case of a POST request. """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(Amenity.select(), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = Amenity(name=request.form['name']) record.save() return jsonify(record.to_hash()) # return 409 if amenity with given name already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10003, msg="Name already exists" )
def get_amenity_by_place(id): amenities = [] query = Amenity.select().where(Place.id == id) for i in query: amenities.append(i.to_hash()) return jsonify(amenities)
def amenities(): """Handle GET and POST requests to /amenities route. Return a list of all amenities in database in the case of a GET request. Create a new amenity record in the database in the case of a POST request. """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = [] for record in Amenity.select(): hash = record.to_hash() list.append(hash) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = Amenity(name=request.form['name']) record.save() return jsonify(record.to_hash()) # return 409 if amenity with given name already exists except IntegrityError: return json_response(add_status_=False, status_=409, code=10003, msg="Name already exists")
def place_amenity_id(place_id, amenity_id): query = Place.select().where(Place.id == place_id) if query.wrapped_count() < 1: return json_response(status_=404, msg="that place does not exist") query = Amenity.select().where(Amenity.id == amenity_id) if query.wrapped_count() < 1: return json_response(status_=404, msg="that amenity does not exist") query = PlaceAmenities.select().where(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) if query.wrapped_count() > 0: return json_response(status_=404, msg="amenity already set for given place") if request.method == "POST": insert = PlaceAmenities(place=place_id, amenity=amenity_id) insert.save() return jsonify(insert.to_dict()), 201 elif request.method == "DELETE": amenity = PlaceAmenities.get(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) amenity.delete_instance() amenity.save() return json_response(status_=200, msg="amentiy delete for given place")
def create_amenity(): """ Create a amenity """ data = request.form try: if 'name' not in data: raise KeyError("'name'") check_amenity = Amenity.select(). where(Amenity.name == data['name']) if check_amenity: return {'code': 10003, 'msg': 'Name already exists'}, 409 new = Amenity.create( name=data['name'] ) res = {} res['code'] = 201 res['msg'] = "Amenity was created successfully" return res, 201 except KeyError as e: res = {} res['code'] = 40000 res['msg'] = 'missing parameters' return res, 400 except Exception as error: response = {} response['code'] = 409 response['msg'] = str(error) return response, 409
def get_place_amenities(place_id): """ Get amenities for place Return a list of all amenities for a place --- tags: - Amenity parameters: - in: path name: place_id type: string required: True description: ID of the place responses: 200: description: List of all amenities for the place schema: $ref: '#/definitions/get_amenities_get_Amenities' """ try: ''' Check if the place exists ''' query = Place.select().where(Place.id == place_id) if not query.exists(): raise LookupError('place_id') ''' Return amenities for the given place ''' data = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id) return ListStyle.list(data, request), 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def get_amenities(): amenities = [] query = Amenity.select() for i in query: amenities.append(i.to_hash()) return jsonify(amenities)
def get_amenity(amenity_id): """ Get the given amenity Return the given amenity in the database. --- tags: - Amenity parameters: - in: path name: amenity_id type: string required: True description: ID of the amenity responses: 200: description: Amenity returned successfully schema: id: Amenity required: - name - id - created_at - updated_at properties: name: type: string description: Name of the amenity default: "Swimming Pool" id: type: number description: id of the amenity default: 1 created_at: type: datetime string description: date and time the amenity was created in the database default: '2016-08-11 20:30:38' updated_at: type: datetime string description: date and time the amenity was updated in the database default: '2016-08-11 20:30:38' 404: description: Amenity was not found 500: description: Request could not be processed """ try: ''' Check if amenity exists ''' query = Amenity.select().where(Amenity.id == amenity_id) if not query.exists(): raise LookupError('amenity_id') ''' Return amenity data ''' amenity = Amenity.get(Amenity.id == amenity_id) return amenity.to_dict(), 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def app_amenities_place(place_id): if request.method == "GET": try: query = Amenity.select().join(PlaceAmenities).where( PlaceAmenities.place == place_id) return ListStyles.list(query, request), 200 except: return jsonify({"code": 404, "msg": "not found"}), 404
def amenities_id(amenity_id): amenity = Amenity.select().where(id=amenity_id).get() if request.method == 'GET': return amenity.to_hash() elif request.method == 'DELETE': amenity.delete_instance()
def amenities_place(place_id): if request.method == "GET": try: query = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id) return ListStyle.list(query, request), 200 except: return json_response(status_=404, msg="Not found")
def get_statdasfde_by_id(amen_id): amens = Amenity.select().where(Amenity.id == int(amen_id)) amen = None for u in amens: amen = u if amen == None: return "Failed" return jsonify(amen.to_hash())
def get_staasedfazte_by_id(amen_id): amens = Amenity.select().where(Amenity.id == int(amen_id)) amen = None for u in amens: amen = u if amen == None: return "Failed" amen.delete_instance() return "Success"
def create_amenities(): data = request.form check_amenity = Amenity.select(). where(Amenity.name == data['name']) if check_amenity: return {'code': 10003, 'msg': 'Name already exists'}, 409 amenity = Amenity.create( name = data['name'] ) return {'code': 201, 'msg': 'Amenity created successfully'}, 201
def place_amenities(place_id): # need to test and correct this request handler query = (Amenity.select().join( PlaceAmenities, on=(Amenity.id == PlaceAmenities.amenity)).join( Place, on=(Place.id == PlaceAmenities.place)).where( Place.id == place_id).get()) for record in query: hash = record.to_hash() list.append(hash) return jsonify(list)
def handle_amenity(): '''Returns all amenities as JSON objects in an array with a GET request. Adds an amenity with a POST request. ''' if request.method == 'GET': list = ListStyle().list(Amenity.select(), request) return jsonify(list), 200 elif request.method == 'POST': try: Amenity.select().where(Amenity.name == request.form['name']).get() return jsonify(code=10003, msg="Name already exists"), 409 except Amenity.DoesNotExist: '''Check that all the required parameters are made in request.''' required = set(["name"]) <= set(request.values.keys()) if required is False: return jsonify(msg="Missing parameter."), 400 amenity = Amenity.create(name=request.form['name']) return jsonify(amenity.to_dict()), 200
def amenities(): if request.method == 'GET': list_amenities = Amenity.select() return json_dumps(list_amenities.to_hash()) elif request.method == 'POST': data = request.data name = data['name'] entry = Amenity.insert(name=name) entry.execute()
def list_select_amenities(place_id): try: Place.get(Place.id == place_id) except Place.DoesNotExist: return jsonify({'code': 404, 'msg': ' place not found'}), 404 list = ListStyle.list(Amenity.select() .join(PlaceAmenities) .where(Amenity.id == PlaceAmenities.amenity) .where(PlaceAmenities.place == place_id), request) return jsonify(list)
def delete_amenity(amenity_id): """ Delete the given amenity Deletes the given amenity in the database. --- tags: - Amenity parameters: - in: path name: amenity_id type: string required: True description: ID of the amenity responses: 200: description: Amenity deleted successfully schema: id: delete_200 required: - code - msg properties: code: type: integer description: Response code from the API default: 200 msg: type: string description: Message about record deletion default: "deleted successfully" 404: description: Amenity was not found 500: description: Request could not be processed """ try: ''' Check if amenity exists ''' query = Amenity.select().where(Amenity.id == amenity_id) if not query.exists(): raise LookupError('amenity_id') ''' Delete the amenity ''' amenity = Amenity.delete().where(Amenity.id == amenity_id) amenity.execute() res = {} res['code'] = 200 res['msg'] = "Amenity was deleted successfully" return res, 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def list_select_amenities(place_id): try: Place.get(Place.id == place_id) except Place.DoesNotExist: return jsonify({'code': 404, 'msg': ' place not found'}), 404 list = ListStyle.list( Amenity.select().join(PlaceAmenities).where( Amenity.id == PlaceAmenities.amenity).where( PlaceAmenities.place == place_id), request) return jsonify(list)
def amenities(): if request.method == 'GET': amenities_list = [] amenities = Amenity.select() for amenity in amenities: amenities_list.append(amenity.to_hash()) return jsonify(amenities_list) elif request.method == 'POST': amenities = Amenity.select() for amenity in amenities: if amenity.name == request.form['name']: message = { 'code': 10003, 'msg': 'Amenity already exists', } res = jsonify(message) res.status_code = 409 return res else: new_amenity = Amenity.create(name=request.form['name']) return jsonify(new_amenity.to_hash())
def amenities(): if request.method == 'GET': amenities = Amenity.select() return ListStyle.list(amenities, request), 200 elif request.method == 'POST': try: if "name" not in request.form: return json_response(status_=400, msg="missing parameters", code=40000) test = Amenity.select().where(Amenity.name == request.form["name"]) if test.wrapped_count() > 0: return json_response(status_=409, code=10002, msg="place already exists with this name") amenity = Amenity(name=request.form["name"]) amenity.save() return jsonify(amenity.to_dict()), 201 except IntegrityError: return json_response(status_=409, msg="Name already exists", code=10003)
def subtest_createWithAllParams(self): """ Test proper creation of an amenity record upon POST request to the API with all parameters provided. """ POST_request1 = self.createAmenityViaAPI() self.assertEqual(POST_request1.status[:3], '200') now = datetime.now().strftime('%d/%m/%Y %H:%M') self.assertEqual(Amenity.get(Amenity.id == 1).name, 'amenity_name') self.assertEqual(Amenity.get(Amenity.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now) self.assertEqual(Amenity.get(Amenity.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now) # test that placebook ID for sole record in database is correct self.assertEqual(Amenity.select().get().id, 1)
def app_amenities(): if request.method == "GET": try: query = Amenity.select() if not query.exists(): return jsonify({"code": 404, "msg": "not found"}), 404 return ListStyles.list(query, request), 200 except: return jsonify({"code": 404, "msg": "not found"}), 404 elif request.method == "POST": try: new = Amenity.create(name=request.form['name']) return jsonify(new.to_dict()), 201 except: return jsonify({"code": 10003, "msg": "Name already exists"}), 409
def create_new_amenity_in_place(place_id, amenity_id): """ Add an amenity to a place Adds an amenity to the referenced place. --- tags: - amenity responses: 200: description: Success message schema: id: success_message properties: status: type: number description: status code default: 200 msg: type: string description: Status message default: 'Success' 400: description: Error message schema: id: error_message properties: status: type: number description: status code default: 400 msg: type: string description: Status message default: 'Error' """ try: pas = PlaceAmenities.select().where(PlaceAmenities.place.id == int(place_id)) amens = Amenity.select().where(Amenity.id == int(amen_id)) if pas == None or amens == None: raise Exception place_amenity = app.models.place_amenity.PlaceAmenities() place_amenity.place = pas place_amenity.amenity = amens place_amenity.save() except: return error_msg(400, 400, "Error") return error_msg(200, 200, "Success")
def handle_amenity_id(amenity_id): '''Returns a JSON object of the amenity with the id passed as parameter with a GET request method. Removes an amenity with DELETE request method. Keyword arguments: amenity_id: The id of the amenity. ''' try: amenity = Amenity.select().where(Amenity.id == amenity_id).get() except Amenity.DoesNotExist: raise Exception("There is no amenity with this id.") if request.method == 'GET': return jsonify(amenity.to_dict()), 200 elif request.method == 'DELETE': amenity = Amenity.delete().where(Amenity.id == amenity_id) amenity.execute() return jsonify(msg="Amenity deleted successfully."), 200
def handle_place_id_amenity(place_id): '''Returns all amenities of the place_id as JSON objects in an array with a GET request. Keyword arguments: place_id: The id of the amenity. ''' try: PlaceAmenities.select().where(PlaceAmenities.place == place_id).get() except PlaceAmenities.DoesNotExist: return jsonify(msg="Amenity does not exist."), 404 if request.method == 'GET': '''Use a join statement to get the instances in the amenity table.''' list = ListStyle().list((Amenity.select().join( PlaceAmenities, on=PlaceAmenities.amenity).where( PlaceAmenities.place == place_id)), request) return jsonify(list), 200
def delete_one_amenity(amen_id): """ Delete an amenity Deletes an amenity based on id. --- tags: - amenity responses: 200: description: Success message schema: id: success_message properties: status: type: number description: status code default: 200 msg: type: string description: Status message default: 'Success' 400: description: Error message schema: id: error_message properties: status: type: number description: status code default: 400 msg: type: string description: Status message default: 'Error' """ amens = Amenity.select().where(Amenity.id == int(amen_id)) amen = None for u in amens: amen = u if amen == None: return error_msg(400, 400, "Error") amen.delete_instance() return error_msg(200, 200, "Success")
def subtest_createWithAllParams(self): """ Test proper creation of an amenity record upon POST request to the API with all parameters provided. """ POST_request1 = self.createAmenityViaAPI() self.assertEqual(POST_request1.status[:3], '200') now = datetime.now().strftime('%d/%m/%Y %H:%M') self.assertEqual(Amenity.get(Amenity.id == 1).name, 'amenity_name') self.assertEqual( Amenity.get(Amenity.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now) self.assertEqual( Amenity.get(Amenity.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now) # test that placebook ID for sole record in database is correct self.assertEqual(Amenity.select().get().id, 1)
def amenities_id(amenity_id): if request.method == 'GET': try: amenity = Amenity.select().where(Amenity.id == amenity_id) except Amenity.DoesNotExist: return json_response(status_=404, msg="Not found") return jsonify(amenity.to_dict()), 200 elif request.method == 'DELETE': try: amenity = Amenity.get(Amenity.id == amenity_id) except Amenity.DoesNotExist: return json_response(status_=404, msg="Not found") amenity.delete_instance() amenity.save() return json_response(status_=200, msg="Amenity deleted")
def get_all_amenities(): """ Get all amenities List all amenities in the database. --- tags: - amenity responses: 200: description: List of all amenities schema: id: amenities_array properties: amenities: type: array description: amenities array items: properties: name: type: string description: name of the amenity default: "flush toilets" id: type: number description: id of the amenity default: 0 created_at: type: datetime string description: date and time the amenity was created default: '2016-08-11 20:30:38.959846' updated_at: type: datetime string description: date and time the amenity was updated default: '2016-08-11 20:30:38.959846' default: [{"name": "flush toilets", "id": 0, "created_at": '2016-08-11 20:30:38.959846', "updated_at": '2016-08-11 20:30:38.959846'}, {"name": "hammock", "id": 1, "created_at": '2016-08-11 20:30:38.959846', "updated_at": '2016-08-11 20:30:38.959846'}] """ amenities = [] for amenity in Amenity.select(): amenities.append(amenity.to_dict()) return jsonify({"amenities": amenities})
def get_amenities(): """ Get all amenities List all amenities in the database. --- tags: - Amenity responses: 200: description: List of all amenities schema: id: Amenities required: - data - paging properties: data: type: array description: amenities array items: $ref: '#/definitions/get_amenity_get_Amenity' paging: description: pagination schema: id: Paging required: - next - prev properties: next: type: string description: next page URL default: "/<path>?page=3&number=10" prev: type: string description: previous page URL default: "/<path>?page=1&number=10" """ data = Amenity.select() return ListStyle.list(data, request), 200
def get_amenity_by_id(amen_id): """ Get one amenity Returns information about one amenity. --- tags: - amenity responses: 200: description: Information about one amenity schema: id: amenity properties: name: type: string description: name of the amenity default: "flush toilets" id: type: number description: id of the amenity default: 0 created_at: type: datetime string description: date and time the amenity was created default: '2016-08-11 20:30:38.959846' updated_at: type: datetime string description: date and time the amenity was updated default: '2016-08-11 20:30:38.959846' """ amens = Amenity.select().where(Amenity.id == int(amen_id)) amen = None for u in amens: amen = u if amen == None: return error_msg(400, 400, "Error") return jsonify(amen.to_dict())
def list_amenities(): try: list = ListStyle.list(Amenity.select(), request) return jsonify(list) except: return jsonify({'code': 404, 'msg': 'not found'}), 404
def get_all_amenities(): amenities = [] for amenity in Amenity.select(): amenities.append(amenity.to_hash()) return jsonify({"amenities": amenities})
def get_amenities(): """ Get all amenities """ data = Amenity.select() return ListStyle.list(data, request), 200
def create_amenity(): """ Create a new amenity Create a new amenity in the database. --- tags: - Amenity parameters: - name: name in: form type: string required: True description: Name of the amenity responses: 201: description: Amenity was created schema: id: post_success required: - code - id - msg properties: code: type: integer description: Response code from the API default: 201 id: type: integer description: ID of the newly created record default: 1 msg: type: string description: Message about record creation default: "created successfully" 400: description: Issue with amenity request 409: description: Amenity already exists 500: description: The request was not able to be processed """ data = {} if request.json: data = request.json else: for key in request.form.keys(): for value in request.form.getlist(key): data[key] = value try: ''' Check if name for amenity was given ''' if not 'name' in data: raise KeyError("'name'") ''' Check if name is a string ''' if not type_test(data['name'], 'string'): raise TypeError("amenity 'name' must be a string value") ''' Check if amenity already exists ''' query = Amenity.select().where(Amenity.name == data['name']) if query.exists(): raise ValueError('amenity already exists') ''' Create new amenity ''' new = Amenity.create( name = data['name'] ) res = {} res['code'] = 201 res['id'] = new.id res['msg'] = "amenity was created successfully" return res, 201 except KeyError as e: res = {} res['code'] = 40000 res['msg'] = 'missing parameters' return res, 400 except TypeError as e: res = {} res['code'] = 400 res['msg'] = e.message return res, 400 except ValueError as e: res = {} res['code'] = 10003 res['msg'] = e.message return res, 409 except Exception as e: abort(500)
def delete_place_amenity(place_id, amenity_id): """ Delete the given amenity Deletes the given amenity in the database. --- tags: - Amenity parameters: - name: place_id in: path type: string required: True description: ID of the given place - name: amenity_id in: path type: string required: True description: ID of the given amenity responses: 200: description: Amenity deleted successfully schema: $ref: '#/definitions/delete_amenity_delete_delete_200' required: - code - msg 404: description: Amenity was not found 500: description: Request could not be processed """ try: ''' Check if place_id is valid ''' query = Place.select().where(Place.id == place_id) if not query.exists(): raise LookupError('place_id') ''' Check if amenity_id is valid ''' query = Amenity.select().where(Amenity.id == amenity_id) if not query.exists(): raise LookupError('amenity_id') ''' Check if amenity is already added for place ''' query = PlaceAmenities.select().where(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) if not query.exists(): raise LookupError('amenity_id, place_id') ''' Add amenity for place ''' delete = PlaceAmenities.delete().where( PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id ) delete.execute() res = {} res['code'] = 200 res['msg'] = 'Amenity deleted successfully for the given place' return res, 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def post_place_amenity(place_id, amenity_id): """ Create a new amenity for place Create a new amenity in the database for the given place --- tags: - Amenity parameters: - name: place_id in: path type: string required: True description: ID of the given place - name: amenity_id in: path type: string required: True description: ID of the given amenity responses: 201: description: Amenity was created schema: $ref: '#/definitions/create_amenity_post_post_success' 400: description: Issue with amenity request 409: description: Amenity already exists 500: description: The request was not able to be processed """ try: ''' Check if place_id is valid ''' query = Place.select().where(Place.id == place_id) if not query.exists(): raise LookupError('place_id') ''' Check if amenity_id is valid ''' query = Amenity.select().where(Amenity.id == amenity_id) if not query.exists(): raise LookupError('amenity_id') ''' Check if amenity is already added for place ''' query = PlaceAmenities.select().where(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id) if query.exists(): raise ValueError('Amenity is already set for the given place') ''' Add amenity for place ''' new = PlaceAmenities.create( place = place_id, amenity = amenity_id ) res = { 'code': 201, 'msg': 'Amenity added successfully for the given place' } return res, 201 except LookupError as e: abort(404) except ValueError as e: res = {} res['code'] = 400 res['msg'] = e.message return res, res['code'] except Exception as e: abort(500)