Пример #1
0
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
Пример #2
0
def handle_place_availibility(place_id):
    '''Checks to see if a place is available on a particular date that is
    passed as parameter with a POST request. Data required is 'year', 'month',
    and 'day'.

    Keyword arguments:
    place_id -- The id of the place to determine if the date is already booked.
    '''
    if request.method == 'POST':
        try:
            Place.select().where(Place.id == place_id).get()
        except Place.DoesNotExist:
            return jsonify("No place exists with this id."), 400
        '''Check that all the required parameters are made in request.'''
        required = set(["year", "month", "day"]) <= set(request.values.keys())
        if required is False:
            return jsonify(msg="Missing parameter."), 400

        date_requested = ''
        for param in ['year', 'month', 'day']:
            date_requested += request.form[param] + '/'

        book_inquiry = datetime.strptime(date_requested[:-1], "%Y/%m/%d")

        arr = []
        for place_book in (PlaceBook.select().where(
                PlaceBook.place == place_id).iterator()):
            start = place_book.date_start
            end = start + timedelta(days=place_book.number_nights)

            if book_inquiry >= start and book_inquiry < end:
                return jsonify(available=False), 200

        return jsonify(available=True), 200
Пример #3
0
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
Пример #4
0
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
Пример #5
0
def create_new_booking(place_id):
    content = request.get_json()
    if not all(param in content.keys() for param in ["user", "is_validated", "date_start", "number_nights"]):
        #ERROR
        return "Failed: bad input"
    try:
        users = User.select().where(User.id == int(user_id))
        user = None
        for u in users:
            user = u
        if user == None:
            return "Failed, user does not exist"

        places = Place.select().where(Place.id == int(place_id))
        place = None
        for u in places:
            place = u
        if place == None:
            return "Failed, place does not exist"

        placebook = PlaceBook()
        placebook.user = user
        placebook.place = place
        placebook.is_validated = content["is_validated"]
        placebook.date_start = content["date_start"]
        placebook.number_nights = content["number_nights"]
        placebook.save()
    except Exception as e:
        return "Failed"
    return "Success"
Пример #6
0
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
Пример #7
0
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)
Пример #8
0
def places_in_state(state_id):
    try:
        State.get(State.id == state_id)
    except State.DoesNotExist:
        return jsonify({'code': 404, 'msg': "State does not exist in the database"}), 404
    query = Place.select().join(City).join(State).where(State.id == state_id)
    return ListStyles.list(query, request), 200
Пример #9
0
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
Пример #10
0
    def subtest_createWithAllParams(self):
        """
        Test proper creation of a place record upon POST request to the API
        with all parameters provided.
        """
        POST_request1 = self.createPlaceViaAPI()
        self.assertEqual(POST_request1.status[:3], '200')

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        # self.assertEqual(Place.get(Place.id == 1).owner.id, 1)
        # self.assertEqual(Place.get(Place.id == 1).city.id, 1)
        # self.assertEqual(Place.get(Place.id == 1).name, "foo")
        # self.assertEqual(Place.get(Place.id == 1).description, "foo description")
        # self.assertEqual(Place.get(Place.id == 1).number_rooms, 1)
        # self.assertEqual(Place.get(Place.id == 1).number_bathrooms, 1)
        # self.assertEqual(Place.get(Place.id == 1).max_guest, 1)
        # self.assertEqual(Place.get(Place.id == 1).price_by_night, 1)
        # self.assertEqual(Place.get(Place.id == 1).latitude, 22.0)
        # self.assertEqual(Place.get(Place.id == 1).longitude, 22.0)
        # self.assertEqual(Place.get(Place.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        # self.assertEqual(Place.get(Place.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test that place ID for sole record in database is correct
        self.assertEqual(Place.select().get().id, 1)
Пример #11
0
def modify_place(place_id):
    id = place_id
    if request.method == 'GET':
        try:
            get_place = Place.get(Place.id == id).to_dict()
            return jsonify(get_place)
        except:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Place not found'}), 404)
    elif request.method == 'PUT':
        place = Place.select().where(Place.id == place_id).get()
        params = request.values
        for key in params:
            if key == 'owner' or key == 'city':
                return jsonify(msg="You may not update the %s." % key), 409
            if key == 'updated_at' or key == 'created_at':
                continue
            else:
                setattr(place, key, params.get(key))
        place.save()
        return jsonify(msg="Place information updated successfully."), 200

    elif request.method == 'DELETE':
        try:
            get_place = Place.get(Place.id == id)
            get_place.delete_instance()
            return "Place with id = %d was deleted\n" % (int(id))
        except:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Place not found'}), 404)
Пример #12
0
def places():
    """Handle GET and POST requests to /places route.

    Return a list of all places in the database in the case of a GET request.
    Create a new place record in the database in the case of a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = ListStyle.list(Place.select(), request)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = Place( owner=request.form['owner_id'],
                        city=request.form['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'] )
        record.save()
        return jsonify(record.to_hash())
Пример #13
0
    def subtest_createWithAllParams(self):
        """
        Test proper creation of a place record upon POST request to the API
        with all parameters provided.
        """
        POST_request1 = self.createPlaceViaAPI()
        self.assertEqual(POST_request1.status[:3], '200')

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        # self.assertEqual(Place.get(Place.id == 1).owner.id, 1)
        # self.assertEqual(Place.get(Place.id == 1).city.id, 1)
        # self.assertEqual(Place.get(Place.id == 1).name, "foo")
        # self.assertEqual(Place.get(Place.id == 1).description, "foo description")
        # self.assertEqual(Place.get(Place.id == 1).number_rooms, 1)
        # self.assertEqual(Place.get(Place.id == 1).number_bathrooms, 1)
        # self.assertEqual(Place.get(Place.id == 1).max_guest, 1)
        # self.assertEqual(Place.get(Place.id == 1).price_by_night, 1)
        # self.assertEqual(Place.get(Place.id == 1).latitude, 22.0)
        # self.assertEqual(Place.get(Place.id == 1).longitude, 22.0)
        # self.assertEqual(Place.get(Place.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        # self.assertEqual(Place.get(Place.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test that place ID for sole record in database is correct
        self.assertEqual(Place.select().get().id, 1)
Пример #14
0
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")
Пример #15
0
def places():
    """Handle GET and POST requests to /places route.

    Return a list of all places in the database in the case of a GET request.
    Create a new place record in the database in the case of a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = []
        for record in Place.select():
            hash = record.to_hash()
            list.append(hash)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = Place(owner=request.form['owner_id'],
                       city=request.form['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'])
        record.save()
        return jsonify(record.to_hash())
Пример #16
0
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
Пример #17
0
 def update_place(book, place_id):
     places = Place.select().where(Place.id == int(place_id))
     place = None
     for u in places:
         place = u
     if place == None:
         return error_msg(400, 400, "place does not exist")
     book.place = place
Пример #18
0
 def update_place(book, place_id):
     places = Place.select().where(Place.id == int(place_id))
     place = None
     for u in places:
         place = u
     if place == None:
         return "Failed, place does not exist"
     book.place = place
Пример #19
0
def places_in_city(state_id, city_id):
    if request.method == 'GET':
        places_list = []
        places = Place.select().join(City).where(Place.city == city_id,
                                                 City.state == state_id)
        for place in places:
            places_list.append(place.to_hash())
        return jsonify(places_list)
Пример #20
0
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)
Пример #21
0
def delete_booking(place_id, book_id):
    """
    Delete the given booking
    Deletes the given booking in the database.
    ---
    tags:
        - PlaceBook
    parameters:
        -
            in: path
            name: place_id
            type: integer
            required: True
            description: ID of the place
        -
            in: path
            name: book_id
            type: integer
            required: True
            description: ID of the booking
    responses:
        200:
            description: Booking deleted successfully
            schema:
                $ref: '#/definitions/delete_amenity_delete_delete_200'
        404:
            description: Booking was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Test if place does not exist '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Test if booking does not exist '''
        query = PlaceBook.select().where(PlaceBook.id == book_id)
        if not query.exists():
            raise LookupError('book_id')

        ''' Check if place, booking combo exists '''
        query = query.where(PlaceBook.place == place_id)
        if not query.exists():
            raise LookupError('book_id, place_id')

        ''' Delete the given booking '''
        booking = PlaceBook.delete().where(PlaceBook.id == book_id, PlaceBook.place == place_id)
        booking.execute()
        res = {}
        res['code'] = 200
        res['msg'] = "Booking was deleted successfully"
        return res, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Пример #22
0
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")
Пример #23
0
def places_by_city(state_id, city_id):
    try:
       city_query = City.get(City.id == city_id, City.state == state_id)
    except:
        return {"code":404, "msg":"not found"}, 404
    places = []
    query = Place.select().where(Place.city == city_query.id)
    for place in query:
        places.append(place.to_hash())
    return jsonify(places)
Пример #24
0
def handle_place_reviews(place_id):
    '''Returns an array of reviews of the place with the same id as that of
    the parameter `place_id` with a GET request. Creates a new review with
    the place_id with a POST request. Will not add attributes `updated_at` or
    `created_at`.

    Keyword arguments:
    place_id -- The id of the place to be reviewed.
    '''
    try:
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return jsonify(msg="Place does not exist."), 404

    if request.method == 'GET':
        arr = []
        for review_place in (ReviewPlace
                             .select()
                             .where(ReviewPlace.place == place_id)):
            arr.append(review_place.review.to_dict())
        return jsonify(arr), 200

    elif request.method == 'POST':
        params = request.values
        review = Review()

        '''Check that all the required parameters are made in request.'''
        required = set(["message", "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(review, key, params.get(key))

        review.save()

        '''Save the connection in the ReviewPlace table.'''
        ReviewPlace().create(place=place_id, review=review.id)

        return jsonify(review.to_dict()), 201
Пример #25
0
def place_reviews(place_id):
    try:
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return jsonify({
            'code': 404,
            'msg': "There is no place with this id."
        }), 404

    if request.method == 'GET':
        query = (Review.select().join(ReviewPlace).where(
            ReviewPlace.place == place_id))

        return ListStyles.list(query, request), 200

    elif request.method == 'POST':
        try:
            if request.form['message'] is None or request.form['user'] is None:
                return jsonify({
                    'code': 404,
                    'msg': "Missing required data."
                }), 404
        except KeyError:
            return jsonify({'code': 400, 'msg': "Missing parameter."}), 400

        try:
            review = Review()
            [
                setattr(review, key, value)
                for (key, value) in request.form.items()
                if key != "created_at" and key != "updated_at"
            ]
            review.save()

            ReviewPlace.create(place=place_id, review=review.id)

            return jsonify(review.to_dict()), 201
        except:
            return jsonify({
                "code": 409,
                "msg": "error creating record, check input data"
            }), 409
Пример #26
0
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)
Пример #27
0
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)
Пример #28
0
def handle_place_city_id(state_id, city_id):
    '''With a GET request method, select the places belonging to the particular
    city (based on the city id) and store their hashes in an array to be
    returned. Will not set attribute passed as `updated_at` or `created_at`.

    Keyword arguments:
    state_id: The id of the place.
    city_id: The id of the city.
    '''

    if request.method == 'GET':
        try:
            places = Place.select().where(Place.city == city_id).get()
        except Place.DoesNotExist:
            return jsonify("There is no place with this id, in this state."),
            400

        arr = []
        for place in Place.select().where(Place.city == city_id):
            arr.append(place.to_dict())
        return jsonify(arr), 200

    elif request.method == 'POST':
        params = request.values
        place = Place()
        '''Check that all the required parameters are made in request.'''
        required = set(["owner", "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.city = city_id
        place.save()
        return jsonify(place.to_dict()), 200
Пример #29
0
def edit_books(place_id, book_id):
    if request.method == "GET":
        try:
            query = Place.select().where(Place.id == place_id)

            if not query.exists():
                return json_response(status_=404, msg="place does not exist")

            booking = PlaceBook.get(PlaceBook.id == book_id)
            return jsonify(booking.to_dict()), 200

        except PlaceBook.DoesNotExist:
            return json_response(code=404, status_=404, msg="Not found")

    elif request.method == "PUT":
        try:
            booking = PlaceBook.get(PlaceBook.id == book_id)

            for key in request.form:
                if key == "place":
                    booking.place = request.form[key]

                elif key == "user":
                    return json_response(status_=400,
                                         msg="Cant change user id")

                elif key == "is_validated":
                    booking.is_validated = request.form[key]

                elif key == "date_start":
                    booking.date_start = request.form[key]

                elif key == "number_nights":
                    booking.number_nights = request.form[key]

            booking.save()
            return jsonify(booking.to_dict()), 200

        except PlaceBook.DoesNotExist:
            return json_response(code=404, status_=404, msg="Not found")

    elif request.method == "DELETE":
        try:
            booking = PlaceBook.get(PlaceBook.id == book_id)
            booking.delete_instance()
            booking.save()
            return json_response(status_=200, code=202, msg="Booking deleted")

        except PlaceBook.DoesNotExist:
            return json_response(code=404, status_=404, msg="Not found")
Пример #30
0
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
Пример #31
0
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)
Пример #32
0
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
Пример #33
0
def get_place_reviews(place_id):
	"""
	Get all place reviews
	List all place reviews in the database.
	---
	tags:
	    - Review
	parameters:
		-
			in: path
			name: place_id
			type: string
			required: True
			description: ID of the place
	responses:
	    200:
	        description: List of all place reviews
	        schema:
	            id: PlaceReviews
	            required:
	                - data
	                - paging
	            properties:
	                data:
	                    type: array
	                    description: place reviews array
	                    items:
	                        $ref: '#/definitions/get_place_review_get_PlaceReview'
	                paging:
	                    description: pagination
	                    schema:
	                        $ref: '#/definitions/get_amenities_get_Paging'
	"""
	try:
		''' Test if user_id exists '''
		query = Place.select().where(Place.id == place_id)
		if not query.exists():
			raise LookupError('place_id')

		''' Get list of reviews for the user '''
		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
Пример #34
0
def edit_books(place_id, book_id):
	if request.method == "GET":
		try:
			query = Place.select().where(Place.id == place_id)

			if not query.exists():
				return json_response(status_=404, msg="place does not exist")

			booking = PlaceBook.get(PlaceBook.id == book_id)
			return jsonify(booking.to_dict()), 200

		except PlaceBook.DoesNotExist:
			return json_response(code=404, status_=404, msg="Not found")


	elif request.method == "PUT":
		try:
			booking = PlaceBook.get(PlaceBook.id == book_id)

			for key in request.form:
				if key == "place":
					booking.place = request.form[key]

				elif key == "user":
					return json_response(status_=400, msg="Cant change user id")

				elif key == "is_validated":
					booking.is_validated = request.form[key]

				elif key == "date_start":
					booking.date_start = request.form[key]

				elif key == "number_nights":
					booking.number_nights = request.form[key]

			booking.save()
			return jsonify(booking.to_dict()), 200

		except PlaceBook.DoesNotExist:
			return json_response(code=404, status_=404, msg="Not found")

	elif request.method == "DELETE":
		try:
			booking = PlaceBook.get(PlaceBook.id == book_id)
			booking.delete_instance()
			booking.save()
			return json_response(status_=200, code=202, msg="Booking deleted")

		except PlaceBook.DoesNotExist:
			return json_response(code=404, status_=404, msg="Not found")
Пример #35
0
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
Пример #36
0
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)
Пример #37
0
def delete_place_by_id(place_id):
    """
    Delete a place
    Deletes a place based on id.
    ---
    tags:
      - place
    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:
        places = Place.select().where(Place.id == int(place_id))
        place = None
        for u in places:
            place = u
        if place == None:
            return error_msg(400, 400, "Error")
        place.delete_instance()
    except:
        return error_msg(400, 400, "Error")
    return error_msg(200, 200, "Success")
Пример #38
0
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
Пример #39
0
def create_place_review(place_id):
    data = request.form
    try:
        if not data['user_id']:
            raise KeyError('user_id')
        elif not data['message']:
            raise KeyError('message')
        elif not isinstance(data['message'], unicode):
            raise ValueError('message')
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')
        query = User.select().where(User.id == data['user_id'])
        if not query.exists():
            raise LookupError('user_id')
        new_review = Review(user_id=data['user_id'], message=data['message'])
        if 'stars' in data:
            new_review.stars = data['stars']
        new_review.save()
        new_place_review = ReviewPlace.create(place=place_id,
                                              review=new_review.id)
        res = {}
        res['code'] = 201
        res['msg'] = 'Review was saved successfully'
        res['id'] = new_review.id
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
    except ValueError as e:
        res = {}
        res['code'] = 400
        res['msg'] = str(e.message) + ' is invalid'
        return res, 400
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {}
        res['code'] = 500
        res['msg'] = e.message
        return res, 500
Пример #40
0
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)
Пример #41
0
def list_post_places():
    if request.method == 'GET':
        places_list = Place.select()
        order_values = [i.to_hash() for i in places_list]
        return jsonify(order_values)

    elif request.method == 'POST':
        place_info = Place.create(
            owner_id=request.form['owner_id'],
            city_id=request.form['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'])
        return jsonify(place_info.to_hash())
Пример #42
0
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)
Пример #43
0
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"
Пример #44
0
def place_available(place_id):
	if "year" not in request.form or "month" not in request.form or "day" not in request.form:
		return json_response(status_=400, code=40000, msg="missing parameters")

	place = Place.select().where(Place.id == place_id)

	if place.wrapped_count() < 1:
		return json_response(status_=404, msg="place does not exist")

	request_date = datetime.strptime(str(request.form["day"]) + str(request.form["month"]) + str(request.form["year"]), "%d%m%Y")

	bookings = PlaceBook.select().where(PlaceBook.place == place_id)

	for booking in bookings:
		start_date = datetime.strptime(booking.date_start.strftime("%d%m%Y"), "%d%m%Y")
		end_date = start_date + timedelta(days=booking.number_nights)
		if end_date >= request_date >= start_date:
			return jsonify({'available': False}), 200 

	return jsonify({'available': True}), 200
Пример #45
0
def places():
	if request.method == 'GET':
		list_places = Place.select()
		return json.dumps(list_places.to_hash())

	elif request.method == 'POST':
		data = request.data
		owner = data['owner_id']
		name = data['name']
		city = data['city']
		description = data['description']
		number_rooms = data['number_rooms']
		number_bathrooms = data['number_bathrooms']
		max_guest = data['max_guest']
		price_by_night = data['price_by_night']
		latitude = data['latitude']
		longitude = data['longitude']

		entry = Place.insert(owner=owner_id, name=name, city=city, description=description, number_rooms=number_rooms, number_bathrooms=number_bathrooms, max_guest=max_guest, price_by_night=price_by_night, latitude=latitude, longitude=longitude)
		entry.execute()
Пример #46
0
def delete_place(place_id):
    """
    Delete the given place
    Deletes the given place in the database.
    ---
    tags:
        - Place
    parameters:
        -
            in: path
            name: place_id
            type: integer
            required: True
            description: ID of the place
    responses:
        200:
            description: Place deleted successfully
            schema:
                $ref: '#/definitions/delete_amenity_delete_delete_200'
        404:
            description: Place was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check if place_id exists '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Delete the given place '''
        delete_place = Place.delete().where(Place.id == place_id)
        delete_place.execute()
        response = {}
        response['code'] = 200
        response['msg'] = "Place was deleted"
        return response, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(505)
Пример #47
0
def places():
    if request.method == 'GET':
        places_list = []
        places = Place.select()
        for place in places:
            places_list.append(place.to_hash())
        return jsonify(places_list)

    elif request.method == 'POST':
        new_place = Place.create(
            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'])
        return jsonify(new_place.to_hash())
Пример #48
0
def app_places():
    if request.method == "GET":
        try:
            query = Place.select()
            return ListStyles.list(query, request), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    if request.method == "POST":
        try:
            new = Place.create(
                owner=int(request.form['owner']),
                city=int(request.form['city']),
                name=str(request.form['name']),
                description=str(request.form['description']),
                latitude=float(request.form['latitude']),
                longitude=float(request.form['longitude'])
            )
            return jsonify(new.to_dict()), 201
        except:
            return jsonify({"code": 10004, "msg": "Place cannot be"}), 409  
Пример #49
0
def city_places(state_id, city_id):
    """Handle GET & POST requests to /states/<state_id>/cities/<city_id>/places.

    Return a list of all places in the database in given city in the case of a
    GET request.
    Create a new place record in the given city in the database in the case of
    a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        try:
            list = []
            for record in Place.select().where(Place.city == city_id):
                hash = record.to_hash()
                list.append(hash)
            return jsonify(list)

        # return 404 not found record does not exist
        except Place.DoesNotExist:
            return json_response(add_status_=False,
                                 status_=404,
                                 code=404,
                                 msg="not found")

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = Place(owner=request.form['owner_id'],
                       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'])
        record.save()
        return jsonify(record.to_hash())
Пример #50
0
def city_places(state_id, city_id):
    """Handle GET & POST requests to /states/<state_id>/cities/<city_id>/places.

    Return a list of all places in the database in given city in the case of a
    GET request.
    Create a new place record in the given city in the database in the case of
    a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        try:
            list = ListStyle.list(Place.select().where(Place.city == city_id), request)
            return jsonify(list)

        # return 404 not found record does not exist
        except Place.DoesNotExist:
            return json_response(
                add_status_=False,
                status_=404,
                code=404,
                msg="not found"
            )

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = Place( owner=request.form['owner_id'],
                        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'] )
        record.save()
        return jsonify(record.to_hash())
Пример #51
0
def app_city_places(state_id, city_id):
    if request.method == "GET":
        query = Place.select().join(City).where(Place.city == city_id, City.state == state_id)
        if query.exists():    
            return ListStyles.list(query, request), 200
        else:
            return jsonify({"code": 404, "msg": "not found"}), 404            

    elif request.method == "POST":
        if City.select().where(City.id == city_id, City.state == state_id).exists():
            new = Place.create(
                owner=int(request.form['owner']),
                city=int(city_id),
                name=str(request.form['name']),
                description=str(request.form['description']),
                latitude=float(request.form['latitude']),
                longitude=float(request.form['longitude'])
            )
            return jsonify(new.to_dict()), 201

        else:
            return jsonify({"code": 404, "msg": "City does not exist in this state"}), 404
Пример #52
0
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
Пример #53
0
def get_places():
    places = []
    query = Place.select()
    return ListStyle.list(query,request)