def states(): if request.method == 'GET': #get list states states_list = [] states = State.select() for state in states: states_list.append(state.to_hash()) return jsonify(states_list) elif request.method == 'POST': #create new state post_name = request.form['name'] states = State.select() for state in states: if state.name == post_name: message = { 'code': 10001, 'msg': 'State already exists', } res = jsonify(message) res.status_code = 409 return res else: new_state = State.create(name=post_name) return jsonify(new_state.to_hash())
def handle_states(): '''Returns all the states from the database as JSON objects with a GET request, or adds a new state to the database with a POST request. Refer to exception rules of peewee `get()` method for additional explanation of how the POST request is handled: http://docs.peewee-orm.com/en/latest/peewee/api.html#SelectQuery.get ''' if request.method == 'GET': list = ListStyle().list(State.select(), request) return jsonify(list), 200 elif request.method == 'POST': params = request.values '''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 try: State.select().where(State.name == request.form['name']).get() return jsonify(code=10001, msg="State already exists"), 409 except State.DoesNotExist: state = State.create(name=request.form['name']) return jsonify(state.to_dict()), 201
def get_places_by_city(state_id, city_id): """ Get all places List all places in the given city in the database. --- tags: - Place parameters: - name: state_id in: path type: integer required: True description: ID of the state - name: city_id in: path type: integer required: True description: ID of the city responses: 200: description: List of all places schema: $ref: '#/definitions/get_places_get_Places' """ try: ''' Check if the state_id exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state_id') ''' Check if the city_id exists ''' query = City.select().where(City.id == city_id) if not query.exists(): raise LookupError('city_id') ''' Check if the city_id is associated to the state_id ''' city = City.get(City.id == city_id) query = State.select().where(State.id == city.state, State.id == state_id) if not query.exists(): raise LookupError('city_id, state_id') ''' Return all places in the given city ''' data = Place.select().where(Place.city == city.id) return ListStyle.list(data, request), 200 except LookupError as e: abort(404) except Exception as error: abort(500)
def get_states(): """ Get all states List all states in the database. --- tags: - State responses: 200: description: List of all states schema: id: States required: - data - paging properties: data: type: array description: states array items: $ref: '#/definitions/get_state_get_State' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ try: ''' Returns a list of states in list named result ''' data = State.select() return ListStyle.list(data, request), 200 except Exception as e: abort(500)
def create_state(): """ Create a state """ data = request.form try: if 'name' not in data: raise KeyError('name') state_check = State.select().where(State.name == data['name']) new = State.create(name=data['name']) res = {} res['code'] = 201 res['msg'] = "State was created successfully" return res, 201 except KeyError as e: response = {} response['code'] = 40000 response['msg'] = 'Missing parameters' return response, 400 except Exception as e: response = {} response['code'] = 10001 response['msg'] = "State already exists" return response, 409
def handle_state_id(state_id): '''Select the state with the id from the database and store as the variable `state` with a GET request method. Update the data of the particular state with a PUT request method. This will take the parameters passed and update only those values. Remove the state with this id from the database with a DELETE request method. Keyword arguments: state_id: The id of the state from the database. ''' try: state = State.select().where(State.id == state_id).get() except State.DoesNotExist: return jsonify(msg="There is no state with this id."), 404 if request.method == 'GET': return jsonify(state.to_dict()), 200 elif request.method == 'DELETE': try: state = State.delete().where(State.id == state_id) except State.DoesNotExist: raise Exception("There is no state with this id.") state.execute() return jsonify(msg="State deleted successfully."), 200
def handle_state_id(state_id): '''Select the state with the id from the database and store as the variable `state` with a GET request method. Update the data of the particular state with a PUT request method. This will take the parameters passed and update only those values. Remove the state with this id from the database with a DELETE request method. Keyword arguments: state_id: The id of the state from the database. ''' try: state = State.select().where(State.id == state_id).get() except State.DoesNotExist: return jsonify(msg="There is no state with this id."), 404 if request.method == 'GET': return jsonify(state.to_dict()), 200 elif request.method == 'DELETE': try: state = State.delete().where(State.id == state_id) except State.DoesNotExist: raise Exception("There is no state with this id.") state.execute() return jsonify(msg="State deleted successfully."), 200
def states(): """Handle GET and POST requests to /states route. Return a list of all states in the database in the case of a GET request. Create a new state in the database in the case of a POST request """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = [] for record in State.select(): hash = record.to_hash() list.append(hash) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = State(name=request.form["name"]) record.save() return jsonify(record.to_hash()) # return 409 state with given name already exists except IntegrityError: return json_response(add_status_=False, status_=409, code=10001, msg="State already exists")
def states(): """Handle GET and POST requests to /states route. Return a list of all states in the database in the case of a GET request. Create a new state in the database in the case of a POST request """ # handle GET requests: # -------------------------------------------------------------------------- if request.method == 'GET': list = ListStyle.list(State.select(), request) return jsonify(list) # handle POST requests: # -------------------------------------------------------------------------- elif request.method == 'POST': try: record = State(name=request.form["name"]) record.save() return jsonify(record.to_hash()) # return 409 state with given name already exists except IntegrityError: return json_response( add_status_=False, status_=409, code=10001, msg="State already exists" )
def handle_place_state_id(state_id): '''Retrieve all the places with a state of that passed in the URL. Keyword arguments: state_id -- The id of the state that this place belongs. ''' if request.method == 'GET': try: State.select().where(State.id == state_id).get() except State.DoesNotExist: return jsonify("No state exists with this id."), 400 list = ListStyle().list((Place.select().join(City).join(State).where( State.id == state_id)), request) return jsonify(list), 200
def get_states(): if request.method == 'GET': states = [] query = State.select() for state in query: states.append(state.to_hash()) return jsonify(states)
def del_state(id): id_check = State.select().where(State.id == id) if not id_check: return {'code': 404, 'msg': 'State not found'}, 404 item = State.delete().where(State.id == id) item.execute() return {'code': 200, 'msg': 'Deleted successfully'}, 200
def get_state(state_id): """ Get the given state Returns the given state in the database. --- tags: - State parameters: - in: path name: state_id type: integer required: True description: ID of the state responses: 200: description: State returned successfully schema: id: State required: - name - id - created_at - updated_at properties: name: type: string description: name of the given state default: None id: type: integer description: id of the state default: 1 created_at: type: datetime string description: date and time the state was created in the database default: '2016-08-11 20:30:38' updated_at: type: datetime string description: date and time the state was updated in the database default: '2016-08-11 20:30:38' 404: description: State was not found 500: description: Request could not be processed """ try: ''' Check that state_id exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state_id') state = State.get(State.id == state_id) return state.to_dict(), 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def state_places(state_id): state = State.select().where(State.id == state_id) if state.wrapped_count() < 1: return json_response(status_=404, code=10002, msg="state not found") query = Place.select().join(City).join(State).where(State.id == state_id) return ListStyle.list(query, request)
def state_create_modify(): if request.method == 'GET': state_list = State.select() order_values = [i.to_hash() for i in state_list] return jsonify(order_values) elif request.method == 'POST': check_state_name = State.select().where( State.name == request.form['name']) if check_state_name: error_msg = {'code': 10001, 'msg': 'State already exists'} return jsonify(error_msg) else: state = State.create(name=request.form['name']) return jsonify(state.to_hash())
def create_state(): data = request.form name_check = State.select().where(State.name == data['name']) if name_check: return {'code': 10001, 'msg': 'State already exists'}, 409 state = State.create( name = data['name'] ) return {'code': 201,'msg': 'State was created successfully'}, 201
def create_new_city(state_id): post_data = request.values if 'name' in post_data: city_query = City.select().where(City.name == post_data['name']) state_query = State.select().where(State.id == state_id).get() if city_query.exists(): out = {'code': 10002, 'msg': 'City already exists in this state'} return out, 409 city_row = City.create(state=state_query, name=post_data['name']) return city_row.to_hash() else: return {"code":404, "msg":"not found"}, 404
def state(number): if request.method == 'GET': query = State.get(State.id == number) return query.to_hash() else: try: query = State.select().where(State.id == number).get() except: return {'code':404, 'msg':'state not found'}, 404 out_json = query.to_hash() query.delete_instance() return out_json
def create_new_state(): post_data = request.values if 'name' not in post_data: return {'code':400, 'msg':'bad request'}, 400 state_query = State.select().where(State.name == post_data['name']) if state_query.exists(): out = {'code': 10001, 'msg': 'State already exists'} return out, 409 try: state_row = State.create(name=post_data['name']) return state_row.to_hash() except: return {'code':500, 'msg':'database connection error'}, 500
def app_states(): if request.method == "GET": try: query = State.select() return ListStyles.list(query, request), 200 except State.DoesNotExist: return jsonify({"code": 404, "msg": "No tables exist yet"}), 404 elif request.method == "POST": try: new = State.create(name=str(request.form['name'])) return jsonify(new.to_dict()), 201 except: return jsonify({"code": 10001, "msg": "State already exists"}), 409
def handle_states(): '''Returns all the states from the database as JSON objects with a GET request, or adds a new state to the database with a POST request. Refer to exception rules of peewee `get()` method for additional explanation of how the POST request is handled: http://docs.peewee-orm.com/en/latest/peewee/api.html#SelectQuery.get ''' if request.method == 'GET': list = ListStyle().list(State.select(), request) return jsonify(list), 200 elif request.method == 'POST': params = request.values '''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 try: State.select().where(State.name == request.form['name']).get() return jsonify(code=10001, msg="State already exists"), 409 except State.DoesNotExist: state = State.create(name=request.form['name']) return jsonify(state.to_dict()), 201
def list_of_states(): if request.method == 'GET': list = ListStyle.list(State.select(), request) return jsonify(list) if request.method == 'POST': # name_state = request.form['name'] try: new_state = State(name=request.form['name']) # saving the changes new_state.save() # returning the new information in hash form return "New State entered! -> %s\n" % (new_state.name) except: return make_response(jsonify({'code': 10000, 'msg': 'State already exist'}), 409)
def delete_one_state(state_id): """ Delete an state Deletes an state based on id. --- tags: - state 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: states = State.select().where(State.id == int(state_id)) state = None for u in states: state = u if state == None: return error_msg(400, 400, "Error") state.delete_instance() except: return error_msg(400, 400, "Error") return error_msg(200, 200, "Success")
def states(): if request.method == 'GET': query = State.select() return ListStyle.list(query, request), 200 elif request.method == 'POST': try: if "name" not in request.form: return json_response(status_=400, msg="missing parameters", code=40000) insert = State(name=str(request.form["name"])) insert.save() return jsonify(insert.to_dict()), 201 except IntegrityError: return json_response(status_=409, code=10001, msg="State already exists")
def list_of_states(): if request.method == 'GET': list = ListStyle.list(State.select(), request) return jsonify(list) if request.method == 'POST': # name_state = request.form['name'] try: new_state = State(name=request.form['name']) # saving the changes new_state.save() # returning the new information in hash form return "New State entered! -> %s\n" % (new_state.name) except: return make_response( jsonify({ 'code': 10000, 'msg': 'State already exist' }), 409)
def get_places_by_state(state_id): """ Get all places by state List all places in the given state in the database. --- tags: - Place parameters: - name: state_id in: path type: integer required: True description: ID of the state responses: 200: description: List of all places in state schema: $ref: '#/definitions/get_places_get_Places' """ try: ''' Check if state exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state_id') ''' Create a list of city ids in the state ''' query = City.select().where(City.state == state_id) if not query.exists(): return ListStyle.list(query, request), 200 cities = [] for city in query: cities.append(city.id) ''' Return the places in listed cities ''' data = Place.select().where(Place.city << cities) return ListStyle.list(data, request), 200 except LookupError as e: abort(404) except Exception as e: print e.message abort(500)
def delete_state(state_id): """ Delete the given state Deletes the given state in the database. --- tags: - State parameters: - in: path name: state_id type: string required: True description: ID of the state responses: 200: description: State deleted successfully schema: $ref: '#/definitions/delete_amenity_delete_delete_200' 404: description: State was not found 500: description: Request could not be processed """ try: ''' Check that state_id exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state_id') ''' Delete the given state ''' delete_state = State.delete().where(State.id == state_id) delete_state.execute() response = {} response['code'] = 200 response['msg'] = "State account was deleted" return response, 200 except LookupError as e: abort(404) except Exception as error: abort(500)
def get_all_states(): """ Get all states List all states in the database. --- tags: - state responses: 200: description: List of all states schema: id: states_array properties: states: type: array description: states array items: properties: name: type: string description: name of the state default: "California" id: type: number description: id of the state default: 0 created_at: type: datetime string description: date and time the state was created default: '2016-08-11 20:30:38.959846' updated_at: type: datetime string description: date and time the state was updated default: '2016-08-11 20:30:38.959846' default: [{"name": "California", "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'}] """ states = [] for state in State.select(): states.append(state.to_dict()) return jsonify({"states": states})
def get_statedddd_by_id(state_id): """ Get one state Returns information about one state. --- tags: - state responses: 200: description: Information about one state schema: id: amenity properties: name: type: string description: name of the state default: "California" id: type: number description: id of the state default: 0 created_at: type: datetime string description: date and time the state was created default: '2016-08-11 20:30:38.959846' updated_at: type: datetime string description: date and time the state was updated default: '2016-08-11 20:30:38.959846' """ if not isinstance(int(state_id), int): return error_msg(400, 400, "Error") states = State.select().where(State.id == int(state_id)) state = None for u in states: state = u if state == None: return error_msg(400, 400, "Error") return jsonify(state.to_dict())
def states(state_id=None): if request.method == "GET": if state_id != None: try: state = State.get(State.id == int(state_id)) return state.to_dict() except: pass return { 'code': 404, 'msg': "not found" }, 404 return { 'data': [state.to_dict() for state in State.select()] }, 200 elif request.method == "POST": name = request.form.get('name') try: new_state = State.create(name=name) except IntegrityError: return { 'code': 10001, 'msg': "State already exists" }, 409 except Exception as e: raise e return new_state.to_dict(), 201 elif request.method == "DELETE": if state_id != None: state = None try: state = State.get(State.id == int(state_id)) except: state = None if state != None: state.delete_instance() return {}, 200 return { 'code': 404, 'msg': "not found" }, 404
def test_create(self): """ Test proper creation (or non-creation) of state records upon POST requests to API. """ # test creation of state with all parameters provided in POST request State.drop_table() database.create_tables([State], safe=True) POST_request1 = self.app.post('/states', data=dict( name='namestring' )) self.assertEqual(POST_request1.status[:3], '200') now = datetime.now().strftime('%d/%m/%Y %H:%M') self.assertEqual(State.get(State.id == 1).name, 'namestring') self.assertEqual(State.get(State.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now) self.assertEqual(State.get(State.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now) # test creation of state in all cases of a parameter missing in POST request POST_request2 = self.app.post('/states', data=dict()) self.assertEqual(POST_request2.status[:3], '400') # test that state ID for sole record in database is correct self.assertEqual(State.select().get().id, 1) # test that a post request with a duplicate name value is rejected POST_request3 = self.app.post('/states', data=dict( name='namestring' )) self.assertEqual(POST_request3.status[:3], '409') self.assertEqual(json.loads(POST_request3.data), {'code': 10001, 'msg': 'State already exists'})
def get_all_states(): query = State.select() return ListStyle.list(query,request)
def create_place_by_city(state_id, city_id): """ Create a new place Create a new place in the given city --- tags: - Place parameters: - name: state_id in: path type: integer required: True description: id of the state - name: city_id in: path type: integer required: True description: id of the city - name: owner_id in: form type: integer required: True description: user id of the owner - name: name in: form type: string required: True description: name of the place - name: description in: form type: string description: description of the place - name: number_rooms in: form type: integer description: number of rooms - name: number_bathrooms in: form type: integer description: number of bathrooms - name: max_guest in: form type: integer description: the max number of guests - name: price_by_night in: form type: integer description: the price per night of the location - name: latitude in: form type: float description: the latitude of the place location - name: longitude in: form type: float description: the longitude of the place location responses: 201: description: Place was created schema: $ref: '#/definitions/create_amenity_post_post_success' 400: description: Issue with place request 404: description: Owner or city was not found 500: description: The request was not able to be processed """ try: data = {} for key in request.form.keys(): for value in request.form.getlist(key): data[key] = value ''' Check for required keys ''' if not 'owner_id' in data: raise KeyError('owner_id') if not 'name' in data: raise KeyError('name') ''' Check required key value data types ''' if not type_test(data['owner_id'], int): raise TypeError('owner_id is not an integer') if not type_test(data['name'], 'string'): raise TypeError('name is not a string') ''' Check optional key value data types ''' if 'description' in data and not type_test(data['description'], 'string'): raise TypeError('description is not a string') if 'number_rooms' in data and not type_test(data['number_rooms'], int): raise TypeError('number_rooms is not an integer') if 'number_bathrooms' in data and not type_test(data['number_bathrooms'], int): raise TypeError('number_bathrooms is not an integer') if 'max_guest' in data and not type_test(data['max_guest'], int): raise TypeError('max_guest is not an integer') if 'price_by_night' in data and not type_test(data['price_by_night'], int): raise TypeError('price_by_night is not an integer') if 'latitude' in data and not type_test(data['latitude'], float): raise TypeError('latitude is not a float') if 'longitude' in data and not type_test(data['longitude'], float): raise TypeError('longitude is not a float') ''' Check if the state_id exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state_id') ''' Check if the city_id exists ''' query = City.select().where(City.id == city_id) if not query.exists(): raise LookupError('city_id') ''' Check if the city_id is associated to the state_id ''' city = City.get(City.id == city_id) query = State.select().where(State.id == city.state, State.id == state_id) if not query.exists(): raise LookupError('city_id, state_id') ''' Check if the owner_id exists ''' query = User.select().where(User.id == data['owner_id']) if not query.exists(): raise LookupError('owner_id') new = Place( owner = data['owner_id'], name = data['name'], city = city.id ) if data['description']: new.description = data['description'] if data['number_rooms']: new.number_rooms = data['number_rooms'] if data['number_bathrooms']: new.number_bathrooms = data['number_bathrooms'] if data['max_guest']: new.max_guest = data['max_guest'] if data['price_by_night']: new.price_by_night = data['price_by_night'] if data['latitude']: new.latitude = data['latitude'] if data['longitude']: new.longitude = data['longitude'] new.save() res = {} res['code'] = 201 res['id'] = new.id res['msg'] = "Place was created successfully" return res, 201 except KeyError as e: res = {} res['code'] = 40000 res['msg'] = 'Missing parameters' return res, 400 except LookupError as e: abort(404) except TypeError as e: res = {} res['code'] = 400 res['msg'] = e.message return res, 400 except Exception as e: print e.message abort(500)
def get_states(): """ Get all states """ data = State.select() return ListStyle.list(data, request), 200
def state_city_place(state_id, city_id): if request.method == "GET": try: state_test = State.select().where(State.id == state_id) if state_test.wrapped_count() < 1: return json_response(status_=404, code=10002, msg="state not found") city_test = City.select().where(City.id == city_id) if city_test.wrapped_count() < 1: return json_response(status_=404, code=10002, msg="state not found") query = Place.select().where(Place.city == city_id) return ListStyle.list(query, request), 200 except Place.DoesNotExist: return json_response(status_=404, code=404, msg="not found") elif request.method == "POST": if "name" not in request.form or "owner_id" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") try: city = City.get(City.id == city_id, City.state_id == state_id) except City.DoesNotExist: return json_response(status_=404, msg="City does not exist") try: place = Place(owner=request.form['owner_id'], city=city_id, name=request.form['name']) if request.form['description']: place.description = str(request.form['description']) if request.form['number_rooms']: place.number_rooms = int(request.form['number_rooms']) if request.form['number_bathrooms']: place.number_bathrooms = int(request.form['number_bathrooms']) if request.form['max_guest']: place.max_guest = int(request.form['max_guest']) if request.form['price_by_night']: place.price_by_night = int(request.form['price_by_night']) if request.form['latitude']: place.latitude = float(request.form['latitude']) if request.form['longitude']: place.longitude = float(request.form['longitude']) place.save() except IntegrityError: return json_response(status_=409, msg="Name already exists") return jsonify(place.to_dict()), 201
def get_states(): states = [] query = State.select() for i in query: states.append(i.to_hash()) return jsonify(states), 200
def create_state(): """ Create a new state Create a new state in the database --- tags: - State parameters: - name: name in: form type: string required: True description: Name of the state responses: 201: description: State was created schema: $ref: '#/definitions/create_amenity_post_post_success' 400: description: Issue with state request 409: description: State already exists 500: description: The request was not able to be processed """ data = {} for key in request.form.keys(): for value in request.form.getlist(key): data[key] = value try: ''' Check that name key is in data ''' if not 'name' in data: raise KeyError('name') ''' Check that name key is not null ''' if not data['name']: raise TypeError("'name' cannot be NULL") ''' Check that name key value is a string ''' if not type_test(data['name'], 'string'): raise TypeError("'name' must be a string") ''' Check if state already exists ''' query = State.select().where(State.name == data['name']) if query.exists(): raise ValueError('State already exists') new = State.create( name = data['name'] ) res = {} res['code'] = 201 res['id'] = new.id res['msg'] = "State was created successfully" return res, 201 except TypeError as e: response = {} response['code'] = 400 response['msg'] = e.message return response, 400 except ValueError as e: response = {} response['code'] = 10001 response['msg'] = e.message return response, 409 except KeyError as e: response = {} response['code'] = 40000 response['msg'] = 'Missing parameters' return response, 400 except Exception as e: print e.message abort(500)