def get_places_by_city(state_id, city_id): """ Get a place with id as place_id and state with id as state_id """ city = City.get(City.id == city_id, City.state == state_id) data = Place.select().where(Place.city == city.id) return ListStyle.list(data, request), 200
def get_places(): """ Get all places List all places in the database. --- tags: - Place responses: 200: description: List of all places schema: id: Places required: - data - paging properties: data: type: array description: places array items: $ref: '#/definitions/get_place_get_Place' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ data = Place.select() return ListStyle.list(data, request), 200
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 users(): if request.method == 'GET': try: # Getting all the users list = ListStyle.list(User.select(), request) return jsonify(list) except: return make_response(jsonify({'code': 10000, 'msg': 'users not found'}), 404) elif request.method == 'POST': user_email = request.form["email"] user_password = request.form["password"] user_first_name = request.form["first_name"] user_last_name = request.form["last_name"] try: new_user = User(email=user_email, first_name=user_first_name, last_name=user_last_name, password=md5.new(user_password).hexdigest()) new_user.save() return jsonify(new_user.to_dict()) except: return make_response(jsonify({'code': 10000, 'msg': 'email already exist'}), 409)
def handle_users(): '''Returns all the users from the database as JSON objects with a GET request, or adds a new user 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(User.select(), request) return jsonify(list), 200 elif request.method == 'POST': try: User.select().where(User.email == request.form['email']).get() return jsonify(code=10000, msg="Email already exists"), 409 except User.DoesNotExist: params = request.values user = User() '''Check that all the required parameters are made in request.''' required = set(["first_name", "last_name", "email", "password" ]) <= set(params.keys()) if required is False: return jsonify(msg="Missing parameter."), 400 for key in params: if key == 'updated_at' or key == 'created_at': continue setattr(user, key, params.get(key)) user.save() return jsonify(user.to_dict()), 201
def handle_city(state_id): '''Returns all the cities in the state with the id passed as `state_id` 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((City.select().where(City.state == state_id)), request) return jsonify(list), 200 elif request.method == 'POST': try: City.select().where((City.name == request.form['name']) & (City.state == state_id)).get() return jsonify(code=10002, msg="City already exists in this " + "state"), 409 except City.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 city = City.create(name=request.form['name'], state=state_id) return jsonify(city.to_dict()), 200
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 handle_places(): '''Returns all the places with a GET request, or adds a new city to the database with a POST request. The parameters passed to the POST request iterate through the data and set the corresponding attributes of the instance to be inserted into the database. Will not set attribute passed as `updated_at` or `created_at`. ''' if request.method == 'GET': list = ListStyle().list(Place.select(), request) return jsonify(list), 200 elif request.method == 'POST': params = request.values place = Place() '''Check that all the required parameters are made in request.''' required = set(["owner", "city", "name"]) <= set(request.values.keys()) if required is False: return jsonify(msg="Missing parameter."), 400 for key in params: if key == 'updated_at' or key == 'created_at': continue setattr(place, key, params.get(key)) place.save() return jsonify(place.to_dict()), 200
def find_book(place_id): # Checking if the place exist try: Place.get(Place.id == place_id) except Place.DoesNotExist: return jsonify({'code': 404, 'msg': 'Place not found'}), 404 if request.method == "GET": try: # Selecting the place booked list = ListStyle.list(PlaceBook.select() .where(PlaceBook.place == place_id), request) return jsonify(list) except: return jsonify({'code': 404, 'msg': 'Book not found'}), 404 if request.method == "POST": # cheking if there is a place try: Place.get(Place.id == place_id) except Place.DoesNotExist: return jsonify({'code': 404, 'Place not found': 'hello'}), 404 try: # getting the place get_booking = PlaceBook.get(PlaceBook.place == place_id) # getting the date from start and formatting its date = get_booking.to_dict()['date_start'] # .strftime("%d/%m/%Y") # Getting the duration of the booking duration = get_booking.to_dict()['number_nights'] # Getting the exact day of checkout total_days = (get_booking.to_dict()['date_start'] + timedelta(duration)) # .strftime("%d/%m/%Y") # Create a new booking from POST data for a selected place except: date = datetime(2000, 01, 01) total_days = datetime(2000, 01, 01) # try: get_user = request.form['user_id'] get_date = request.form['date_start'] get_nights = int(request.form['number_nights']) # formatting the date from unicode to datetime to_date = datetime.strptime(get_date, '%Y-%m-%d %H:%M:%S') # Checking if the place is Available in the desired dates if to_date >= date and to_date <= total_days: return make_response( jsonify({'code': '110000', 'msg': "Place unavailable at this date"}), 410) # Booking the place since it is Available new_book = PlaceBook(place=place_id, user=get_user, date_start=get_date, number_nights=get_nights) new_book.save() return jsonify(new_book.to_dict())
def get_users(): """ Get all users List all users in the database. --- tags: - User responses: 200: description: List of all users schema: id: Users required: - data - paging properties: data: type: array description: users array items: $ref: '#/definitions/get_user_get_User' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ data = User.select() return ListStyle.list(data, request), 200
def cities(state_id): if request.method == 'GET': try: query = City.select().where(City.state == state_id) return ListStyle.list(query, request), 200 except City.DoesNotExist: return json_response(status_=404, msg="not found") elif request.method == 'POST': if "name" not in request.form: return json_response(status_=400, msg="missing parameters", code=40000) city_test = City.select().where(City.name == str(request.form["name"]), City.state == state_id) if city_test.wrapped_count() > 0: return json_response(status_=409, code=10002, msg="city already exists in this state") city = City(name=str(request.form["name"]), state=str(state_id)) city.save() return jsonify(city.to_dict()), 201
def users(): if request.method == 'GET': try: # Getting all the users list = ListStyle.list(User.select(), request) return jsonify(list) except: return make_response( jsonify({ 'code': 10000, 'msg': 'users not found' }), 404) elif request.method == 'POST': user_email = request.form["email"] user_password = request.form["password"] user_first_name = request.form["first_name"] user_last_name = request.form["last_name"] try: new_user = User(email=user_email, first_name=user_first_name, last_name=user_last_name, password=md5.new(user_password).hexdigest()) new_user.save() return jsonify(new_user.to_dict()) except: return make_response( jsonify({ 'code': 10000, 'msg': 'email already exist' }), 409)
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 books(place_id): if request.method == 'GET': query = Place.select().where(Place.id == place_id) if not query.exists(): return json_response(status_=404, msg="place does not exist") query = PlaceBook.select().where(PlaceBook.place == place_id) return ListStyle.list(query, request), 200 elif request.method == 'POST': if "name" not in request.form or "date_start" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") test = Place.select().where(Place.id == place_id) if test.wrapped_count() < 1: return json_response(status_=404, code=10002, msg="no place with such id") test = User.select().where(User.id == request.form["user"]) if test.wrapped_count() < 1: return json_response(status_=404, msg="no user with given id") try: start = datetime.strptime(request.form['date_start'], '%Y/%m/%d %H:%M:%S') except ValueError: return json_response(status_=400, msg="incorrect date format") end = start + timedelta(days=int(request.form['number_nights'])) bookings = PlaceBook.select().where(PlaceBook.place == place_id) for booking in bookings: start_b = booking.date_start end_b = start_date + timedelta(days=booking.number_nights) if start >= start_b and start < end_b: return json_response(status=410, msg="Place unavailable at this date", code=110000) elif start_b >= start and start_b < end: return json_response(status=410, msg="Place unavailable at this date", code=110000) elif end > start_b and end <= end_b: return json_response(status=410, msg="Place unavailable at this date", code=110000) place_book = PlaceBook(place=place_id, user=request.form['user'], date_start=datetime.strptime(request.form['date_start'], '%Y/%m/%d %H:%M:%S')) if "is_validated" in request.form: place_book.is_validated = request.form["is_validated"] elif "number_nights" in request.form: place_book.number_nights = request.form["number_nights"] place_book.save() return jsonify(place_book.to_dict()), 201
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 get_places_by_state(state_id): """ Get a place in a state with id as state_id """ try: 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) data = Place.select().where(Place.city << cities) return ListStyle.list(data, request), 200 except Exception as e: res = {} res['code'] = 500 res['msg'] = str(error) return res, 500
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 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 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 get_user_reviews(user_id): """ Get all user reviews List all user reviews in the database. --- tags: - Review parameters: - in: path name: user_id type: string required: True description: ID of the user responses: 200: description: List of all user reviews schema: id: UserReviews required: - data - paging properties: data: type: array description: user reviews array items: $ref: '#/definitions/get_user_review_get_UserReview' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ try: ''' Test if user_id exists ''' query = User.select().where(User.id == user_id) if not query.exists(): raise LookupError('user_id') ''' Get list of reviews for the user and return response ''' reviews = Review.select(Review, ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id) return ListStyle.list(reviews, request), 200 except LookupError as e: abort(404) except Exception as e: print e.message res = { 'code': 500, 'msg': e.message } return res, 500
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 place_reviews(place_id): place_test = Place.select().where(Place.id == place_id) if place_test.wrapped_count() < 1: return json_response(status_=404, msg="place does not exist with that id") if request.method == "GET": query = Review.select(Review, ReviewPlace).join(ReviewPlace).where(ReviewPlace.place == place_id) return ListStyle.list(query, request), 200 elif request.method == "POST": if "message" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") elif "user_id" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") elif "stars" not in request.form: # if type(request.form["message"]) != str: # return json_response(status_=400, msg="invalid data type for message") # if type(request.form["user_id"] != int): # return json_response(status_=400, msg="invalid data type for user id") review = Review(message=str(request.form["message"]), user=request.form["user_id"]) review.save() p_review = ReviewPlace(place=place_id, review=review.id) p_review.save() return jsonify(review.to_dict()), 201 else: # if type(request.form["message"]) != str: # return json_response(status_=400, msg="invalid data type for message") # if type(request.form["user_id"] != int): # return json_response(status_=400, msg="invalid data type for user id") # if type(request.form["stars"] != int): # return json_response(status_=400, msg="invalid data type for stars") review = Review(message=str(request.form["message"]), user=request.form["user_id"], stars=int(request.form["stars"])) review.save() p_review = ReviewPlace(place=place_id, review=review.id) p_review.save() return jsonify(review.to_dict()), 201
def get_place_reviews(place_id): try: query = Place.select().where(Place.id == place_id) if not query.exists(): raise LookupError('place_id') reviews = Review.select( Review, ReviewPlace).join(ReviewPlace).where(ReviewPlace.place == place_id) return ListStyle.list(reviews, request), 200 except LookupError as e: abort(404) except Exception as e: res = {'code': 500, 'msg': e.message} return res, 500
def get_reviews_user(user_id): # Checking if an user exist try: User.get(User.id == user_id) except User.DoesNotExist: return jsonify(msg="There is no user with this id."), 404 # Getting all the review by user id if request.method == "GET": try: # Checking if a review exist on a specific user try: ReviewUser.get(ReviewUser.user == user_id) except: return jsonify( msg="There is no review for an user with this id."), 404 # retriving the reviews an user received list = ListStyle.list( User.select().join(ReviewUser).where( ReviewUser.user == User.id).where( ReviewUser.user == user_id), request) return jsonify(list) except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404) elif request.method == "POST": user_message = request.form["message"] user_stars = request.form["stars"] try: new_review = Review(message=user_message, stars=user_stars, user=user_id) new_review.save() user_review = ReviewUser(user=user_id, review=new_review.id) user_review.save() return jsonify(new_review.to_dict()) except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404)
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 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_place_bookings(place_id): """ Get all bookings List all bookings for a place in the database. --- tags: - PlaceBook parameters: - name: place_id in: path type: integer required: True description: ID of the place responses: 200: description: List of all bookings schema: id: Bookings required: - data - paging properties: data: type: array description: bookings array items: $ref: '#/definitions/get_booking_get_Booking' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ try: ''' Check if place_id exists ''' query = Place.select().where(Place.id == place_id) if not query.exists(): raise LookupError('place_id') ''' Return list of bookings for the given place ''' data = PlaceBook.select().where(PlaceBook.place == place_id) return ListStyle.list(data, request), 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def get_user_reviews(user_id): """ Get user Reviews of user with id as user_id """ try: query = User.select().where(User.id == user_id) if not query.exists(): raise LookupError('user_id') reviews = Review.select( Review, ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id) return ListStyle.list(reviews, request), 200 except LookupError as e: abort(404) except Exception as e: res = {'code': 500, 'msg': e.message} return res, 500
def handle_books(place_id): '''Returns all bookings as JSON objects in an array with a GET request. Adds a booking to the place_id with a POST request. Keyword arguments: place_id: The id of the place with the booking. ''' if request.method == 'GET': list = ListStyle().list( (PlaceBook.select().where(PlaceBook.place == place_id)), request) return jsonify(list), 200 elif request.method == 'POST': try: datetime.strptime(request.form['date_start'], "%Y/%m/%d %H:%M:%S") except ValueError: return jsonify(msg="Incorrect time format: should be " + "yyyy/MM/dd HH:mm:ss"), 409 '''Convert the date_start into a date without time.''' book_inquiry = datetime.strptime(request.form['date_start'], "%Y/%m/%d %H:%M:%S").date() arr = [] for place_book in (PlaceBook.select().where( PlaceBook.place == place_id).iterator()): start = place_book.date_start.date() end = start + timedelta(days=place_book.number_nights) '''Check to see if book_inquiry date is not taken.''' if book_inquiry >= start and book_inquiry < end: return jsonify(available=False), 200 params = request.values book = PlaceBook() '''Check that all the required parameters are made in request.''' required = set(["date_start", "user"]) <= set(request.values.keys()) if required is False: return jsonify(msg="Missing parameter."), 400 for key in params: if key == 'updated_at' or key == 'created_at': continue setattr(book, key, params.get(key)) book.place = place_id book.save() return jsonify(book.to_dict()), 200
def modify_city(state_id, city_id): id = city_id try: if request.method == 'GET': list = ListStyle.list( City.select().where(City.id == city_id and City.state == state_id), request) return jsonify(list) except: return "City with id %d does not exist" % (int(id)) if request.method == "DELETE": id = city_id try: get_city = City.get(City.id == id) get_city.delete_instance() return "City with id %d was deleted\n" % (int(id)) except: return "City with id %d does not exist\n" % (int(id))
def modify_city(state_id, city_id): id = city_id try: if request.method == 'GET': list = ListStyle.list(City.select() .where(City.id == city_id and City.state == state_id), request) return jsonify(list) except: return "City with id %d does not exist" % (int(id)) if request.method == "DELETE": id = city_id try: get_city = City.get(City.id == id) get_city.delete_instance() return "City with id %d was deleted\n" % (int(id)) except: return "City with id %d does not exist\n" % (int(id))
def places(): if request.method == 'GET': list_places = Place.select() return ListStyle.list(list_places, request), 200 elif request.method == 'POST': if "name" not in request.form or "owner_id" not in request.form or "city" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") test = Place.select().where(Place.name == request.form["name"]) if test.wrapped_count() > 0: return json_response(status_=409, code=10002, msg="place already exists with this name") try: entry = Place(owner=request.form["owner_id"], name=request.form["name"], city=request.form["city"]) if request.form['description']: entry.description = str(request.form['description']) if request.form['number_rooms']: entry.number_rooms = int(request.form['number_rooms']) if request.form['number_bathrooms']: entry.number_bathrooms = int(request.form['number_bathrooms']) if request.form['max_guest']: entry.max_guest = int(request.form['max_guest']) if request.form['price_by_night']: entry.price_by_night = int(request.form['price_by_night']) if request.form['latitude']: entry.latitude = float(request.form['latitude']) if request.form['longitude']: entry.longitude = float(request.form['longitude']) entry.save() return jsonify(entry.to_dict()), 201 except IntegrityError: return json_response(status_=400, msg="you are missing a field in your post request")
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 list_cities(state_id): id_state = state_id # returns a json with the cities associated to a state if request.method == 'GET': list = ListStyle.list(City.select() .where(City.state == id_state), request) return jsonify(list) # creates a new city elif request.method == 'POST': # checks if the city already exist in the state for city in City.select(): if str(city.state_id) == id_state and city.name == request.form['name']: return make_response(jsonify({'code': '10001', 'msg': 'City already exists in this state'}), 409) city_name = request.form['name'] new_city = City(name=city_name, state_id=id_state) new_city.save() return "New city saved %s\n" % (new_city.name)
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_list_places(state_id): try: # Checking if a state exist State.get(State.id == state_id) except State.DoesNotExist: return make_response(jsonify({'code': '10001', 'msg': 'Place not found'}), 404) if request.method == 'GET': try: # getting a place that is in a specific state list = ListStyle.list(Place.select() .join(City) .where(Place.city == City.id) .join(State) .where(State.id == City.state), request) return jsonify(list) except: return make_response(jsonify({'code': '10001', 'msg': 'Place not found'}), 404)
def get_review_place(place_id): try: # Checking if place exist Place.select().where(Place.id == place_id).get() except Place.DoesNotExist: return make_response( jsonify({ 'code': 10000, 'msg': 'Place not found' }), 404) if request.method == 'GET': try: # Getting the all the reviews for a place list = ListStyle.list( Review.select().join(ReviewPlace).where( ReviewPlace.review == Review.id).where( ReviewPlace.place == place_id), request) return jsonify(list) except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404) elif request.method == 'POST': user_message = request.form["message"] user_stars = request.form["stars"] try: new_review = Review(message=user_message, stars=user_stars, user=place_id) # using the place_id as user? new_review.save() review_place = ReviewPlace(review=new_review.id, place=place_id) review_place.save() return jsonify(new_review.to_dict()) except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404)
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 list_of_place(): # returning a list of all places if request.method == 'GET': list = ListStyle.list(Place.select(), request) return jsonify(list) if request.method == 'POST': new_place = Place(owner=request.form['owner'], city=request.form['city'], name=request.form['name'], description=request.form['description'], number_rooms=request.form['number_rooms'], number_bathrooms=request.form['number_bathrooms'], max_guest=request.form['max_guest'], price_by_night=request.form['price_by_night'], latitude=request.form['latitude'], longitude=request.form['longitude'] ) new_place.save() return "place created"
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 users(): if request.method == "POST": try: if "email" not in request.form or "password" not in request.form or "first_name" not in request.form or "last_name" not in request.form: return json_response(status_=400, code=40000, msg="missing parameters") new_user = User(email=request.form["email"], password=request.form["password"], first_name=request.form["first_name"], last_name=request.form["last_name"]) new_user.save() return jsonify(new_user.to_dict()), 201 except IntegrityError: return json_response(status_=409, msg="Email already exists", code=10000) elif request.method == "GET": query = User.select() return ListStyle.list(query, request), 200
def get_cities(state_id): """ Get all cities List all cities in the database. --- tags: - City responses: 200: description: List of all cities schema: id: Cities required: - data - paging properties: data: type: array description: cities array items: $ref: '#/definitions/get_city_get_City' paging: description: pagination schema: $ref: '#/definitions/get_amenities_get_Paging' """ try: ''' Check if state exists ''' query = State.select().where(State.id == state_id) if not query.exists(): raise LookupError('state') ''' Return list of cities in given state ''' data = City.select().where(City.state == state_id) return ListStyle.list(data, request), 200 except LookupError as e: abort(404) except Exception as e: abort(500)
def cities(state_id): if request.method == 'GET': try: query = City.select().where(City.state == state_id) return ListStyle.list(query, request), 200 except City.DoesNotExist: return json_response(status_=404, msg="not found") elif request.method == 'POST': if "name" not in request.form: return json_response(status_=400, msg="missing parameters", code=40000) city_test = City.select().where(City.name == str(request.form["name"]), City.state == state_id) if city_test.wrapped_count() > 0: return json_response(status_=409, code=10002, msg="city already exists in this state") city = City(name=str(request.form["name"]), state=str(state_id)) city.save() return jsonify(city.to_dict()), 201
def delete_reviews_place(place_id, review_id): try: # Checking if place exist Place.select().where(Place.id == place_id).get() except Place.DoesNotExist: return make_response(jsonify({'code': 10000, 'msg': 'Not found'}), 404) if request.method == 'GET': try: # Checking if a review exist Review.get(Review.id == review_id) # Getting the review for a place list = ListStyle.list( Review.select().join(ReviewPlace).where( ReviewPlace.review == Review.id).where( ReviewPlace.place == place_id and ReviewPlace.review == review_id), request) return jsonify(list) except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404) elif request.method == 'DELETE': try: place_review = (ReviewPlace.get(ReviewPlace.place == place_id & ReviewPlace.review == review_id)) place_review.delete_instance() get_review = Review.get(Review.id == review_id) get_review.delete_instance() return "Review was deleted" except: return make_response( jsonify({ 'code': 10000, 'msg': 'Review not found' }), 404)
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 list_cities(state_id): id_state = state_id # returns a json with the cities associated to a state if request.method == 'GET': list = ListStyle.list(City.select().where(City.state == id_state), request) return jsonify(list) # creates a new city elif request.method == 'POST': # checks if the city already exist in the state for city in City.select(): if str(city.state_id ) == id_state and city.name == request.form['name']: return make_response( jsonify({ 'code': '10001', 'msg': 'City already exists in this state' }), 409) city_name = request.form['name'] new_city = City(name=city_name, state_id=id_state) new_city.save() return "New city saved %s\n" % (new_city.name)
def places_within_city(state_id, city_id): response = jsonify({'code': 404, 'msg': 'not found'}) response.status_code = 404 # Getting the information for the place if request.method == 'GET': try: list = ListStyle.list(Place.select() .join(City) .where(City.id == city_id) .where(Place.city == city_id, City.state == state_id), request) return jsonify(list) except: return response # Creating a new place elif request.method == 'POST': try: # Getting the city to check if it exist City.get(City.id == city_id, City.state == state_id) # adding city by Using Post add_place = Place.create(owner=request.form['owner'], city=city_id, name=request.form['name'], description=request.form['description'], number_rooms=request.form['number_rooms'], number_bathrooms=request.form['number_bathrooms'], max_guest=request.form['max_guest'], price_by_night=request.form['price_by_night'], latitude=request.form['latitude'], longitude=request.form['longitude']) add_place.save() return jsonify(add_place.to_dict()) print("You've just added a place!") except: return response
def list_amenities(): try: list = ListStyle.list(Amenity.select(), request) return jsonify(list) except: return jsonify({'code': 404, 'msg': 'not found'}), 404
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