示例#1
0
 def tearDown(self):
     #delete all from users
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
示例#2
0
def create_database():
    try:
         User.create_table()
    except peewee.OperationalError:
        pass

    try:
         State.create_table()
    except peewee.OperationalError:
        pass

    try:
         City.create_table()
    except peewee.OperationalError:
        pass

    try:
         Place.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceBook.create_table()
    except peewee.OperationalError:
        pass

    try:
         Amenity.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceAmenities.create_table()
    except peewee.OperationalError:
        pass
示例#3
0
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())
示例#4
0
    def setUp(self):
        # disabling logs
        logging.disable(logging.CRITICAL)
        self.app = app.test_client()
        # connecting to the database
        db.connect()
        # creating tables
        db.create_tables([User], safe=True)
        db.create_tables([State], safe=True)
        db.create_tables([City], safe=True)
        db.create_tables([Place], safe=True)
        db.create_tables([PlaceBook], safe=True)

        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        # Creating a new users
        user1 = User(first_name='Jon',
                     last_name='Snow',
                     email='jon@snow',
                     password='******')
        user1.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()
示例#5
0
 def setUp(self):
     #connect to db and delete everyone in the users table
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
示例#6
0
    def setUp(self):
        # disabling logs
        logging.disable(logging.CRITICAL)
        self.app = app.test_client()
        # connecting to the database
        db.connect()
        # creating tables
        db.create_tables([User], safe=True)
        db.create_tables([State], safe=True)
        db.create_tables([City], safe=True)
        db.create_tables([Place], safe=True)
        db.create_tables([PlaceBook], safe=True)

        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        # Creating a new users
        user1 = User(first_name='Jon',
                     last_name='Snow',
                     email='jon@snow',
                     password='******')
        user1.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()
示例#7
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
示例#8
0
def make_reservation(place_id):
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Place not found'}), 404)
    if request.method == "POST":
        year = int(request.form["year"])
        month = int(request.form["month"])
        day = int(request.form["day"])

        try:
            # getting the place
            get_booking = PlaceBook.get(PlaceBook.place == place_id)

            # Creating a datetime with the post parameters
            date_object = datetime(year, month, day).strftime("%d/%m/%Y")

            # 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")

            if date_object >= date and date_object <= total_days:
                return jsonify({'Available': False})
            else:
                return jsonify({'Available': True})
        except:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Wrong date format'}), 400)
示例#9
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())
示例#10
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
示例#11
0
    def test_review_place3(self):
        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()

        # Creating a review for a place that exist
        new_review = self.app.post('/places/1/reviews',
                                   data=dict(message="I like it",
                                             stars=5))
        assert new_review.status_code == 200

        # Checking for a review that does not exist
        new_review_get = self.app.get('/places/1/reviews/5')
        assert new_review_get.status_code == 404

        # Checking for a place that does not exist
        new_review_get = self.app.get('/places/2/reviews/2')
        assert new_review_get.status_code == 404

        # Checking for a review that does exist
        new_review_get = self.app.get('/places/1/reviews/1')
        assert new_review_get.status_code == 200
示例#12
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)
示例#13
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
示例#14
0
    def test_review_place2(self):
        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()

        # Creating a review for a place that exist
        new_review = self.app.post('/places/1/reviews',
                                   data=dict(message="I like it",
                                             stars=5))
        assert new_review.status_code == 200
        # checking the review id, should be 1
        assert json.loads(new_review.data)["id"] == 1
        # Creating a review for a place that does not exist
        new_review = self.app.post('/places/3/reviews',
                                   data=dict(message="I like it",
                                             user_id=1,
                                             stars=5))
        assert new_review.status_code == 404
示例#15
0
def app_create_delete_amenity(place_id, amenity_id):
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({"code": 409, "msg": "place id does not exist"}), 409
    try:
        Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return jsonify({"code": 409, "msg": "amenity id does not exist"}), 409

    if request.method == "POST":
        if PlaceAmenities.select().where(
                PlaceAmenities.place == place_id,
                PlaceAmenities.amenity == amenity_id).exists():
            return jsonify({
                "code": 409,
                "msg": "Place already has this amenity"
            }), 409

        PlaceAmenities.create(place=place_id, amenity=amenity_id)
        return jsonify({"code": 200, "msg": "success"}), 200

    elif request.method == "DELETE":
        try:
            query = PlaceAmenities.select().where(
                PlaceAmenities.place == place_id,
                PlaceAmenities.amenity == amenity_id).get()
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
示例#16
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
示例#17
0
 def tearDown(self):
     """Remove tables from airbnb_test database upon completion of test."""
     ReviewUser.drop_table()
     ReviewPlace.drop_table()
     Review.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#18
0
 def tearDown(self):
     """
     Remove place table from airbnb_test database upon completion of test
     case.
     """
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#19
0
 def tearDown(self):
     """
     Remove place table from airbnb_test database upon completion of test
     case.
     """
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#20
0
def place_id(place_id):
    """Handle GET, PUT, and DELETE requests to /places/<place_id> route.

    Return a hash of the appropriate record in the case of a GET request.
    Update appropriate hash in database in case of PUT request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Place.get(Place.id == place_id)

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

    # if exception does not arise:
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    elif request.method == 'PUT':
        record = Place.get(Place.id == place_id)
        # code below can be optimized in future using list comprehensions
        for key in request.values.keys():
            if key == "name":
                record.name = request.values[key]
            elif key == "description":
                record.description = request.values[key]
            elif key == "number_rooms":
                record.number_rooms = request.values[key]
            elif key == "number_bathrooms":
                record.number_bathrooms = request.values[key]
            elif key == "max_guest":
                record.max_guest = request.values[key]
            elif key == "price_by_night":
                record.price_by_night = request.values[key]
            elif key == "latitude":
                record.latitude = request.values[key]
            elif key == "longitude":
                record.longitude = request.values[key]
            record.save()
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted city\n'
示例#21
0
 def tearDown(self):
     """
     Remove placebook table from airbnb_test database upon completion of
     test case.
     """
     # drop tables from database
     PlaceBook.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#22
0
 def tearDown(self):
     """
     Remove placebook table from airbnb_test database upon completion of
     test case.
     """
     # drop tables from database
     PlaceBook.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#23
0
def place_id(place_id):
    """Handle GET, PUT, and DELETE requests to /places/<place_id> route.

    Return a hash of the appropriate record in the case of a GET request.
    Update appropriate hash in database in case of PUT request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Place.get(Place.id == place_id)

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

    # if exception does not arise:
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    elif request.method == 'PUT':
        record = Place.get(Place.id == place_id)
        # code below can be optimized in future using list comprehensions
        for key in request.values.keys():
            if key == "name":
                record.name = request.values[key]
            elif key == "description":
                record.description = request.values[key]
            elif key == "number_rooms":
                record.number_rooms = request.values[key]
            elif key == "number_bathrooms":
                record.number_bathrooms = request.values[key]
            elif key == "max_guest":
                record.max_guest = request.values[key]
            elif key == "price_by_night":
                record.price_by_night = request.values[key]
            elif key == "latitude":
                record.latitude = request.values[key]
            elif key == "longitude":
                record.longitude = request.values[key]
            record.save()
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted city\n'
示例#24
0
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)
示例#25
0
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)
示例#26
0
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create review table in airbnb_test database.
        """
        self.app = app.test_client()        # set up test client
        self.app.testing = True             # set testing to True
        logging.disable(logging.CRITICAL)   # disable logs

        database.connect()                          # connect to airbnb_test db
        database.create_tables(                     # create tables
            [User, State, City, Place, Review, ReviewUser, ReviewPlace],
            safe=True
        )

        # create user record for routes
        user_record = User(
            email='anystring',
            password='******',
            first_name='anystring2',
            last_name='anystring3'
        )
        user_record.save()

        user_record2 = User(
            email='anystring-2',
            password='******',
            first_name='anystring2',
            last_name='anystring3'
        )
        user_record2.save()

        # create place records (and dependencies) for routes
        state_record = State(name='foo-statee')
        state_record.save()
        city_record = City(name='foo-city', state=1)
        city_record.save()
        place_record = Place(
            owner_id=1,
            city_id=1,
            name="foo",
            description="foo description",
            number_rooms=1,
            number_bathrooms=1,
            max_guest=1,
            price_by_night=1,
            latitude=20.0,
            longitude=22.0
        )
        place_record.save()
示例#27
0
    def test_update(self):
        """
        test_update tests update of place records upon PUT requests to API
        """
        self.createPlaceViaPeewee()

        PUT_request1 = self.app.put('/places/1', data=dict(
            name="foo-name2",
            description="foo description 2",
            number_rooms=2,
            number_bathrooms=2,
            max_guest=2,
            price_by_night=2,
            latitude=30.0,
            longitude=32.0
        ))
        self.assertEqual(PUT_request1.status[:3], '200')

        self.assertEqual(Place.get(Place.id == 1).name, 'foo-name2')
        self.assertEqual(Place.get(Place.id == 1).description, 'foo description 2')
        self.assertEqual(Place.get(Place.id == 1).number_rooms, 2)
        self.assertEqual(Place.get(Place.id == 1).number_bathrooms, 2)
        self.assertEqual(Place.get(Place.id == 1).max_guest, 2)
        self.assertEqual(Place.get(Place.id == 1).price_by_night, 2)
        self.assertEqual(Place.get(Place.id == 1).latitude, 30.0)
        self.assertEqual(Place.get(Place.id == 1).longitude, 32.0)

        # test response of PUT request for place by place id which does not exist
        PUT_request2 = self.app.put('/places/1000')
        self.assertEqual(PUT_request2.status[:3], '404')
示例#28
0
def delete_place(place_id):
    """
    Delete place with id as place_id
    """
    try:
        place = Place.get(Place.id == place_id)
    except Exception:
        return {'code': 404, 'msg': 'Place not found'}, 404
    delete_place = Place.delete().where(Place.id == place_id)
    delete_place.execute()
    response = {}
    response['code'] = 200
    response['msg'] = "Place was deleted successfully"
    return response, 200
示例#29
0
    def test_update(self):
        """
        test_update tests update of place records upon PUT requests to API
        """
        self.createPlaceViaPeewee()

        PUT_request1 = self.app.put('/places/1',
                                    data=dict(name="foo-name2",
                                              description="foo description 2",
                                              number_rooms=2,
                                              number_bathrooms=2,
                                              max_guest=2,
                                              price_by_night=2,
                                              latitude=30.0,
                                              longitude=32.0))
        self.assertEqual(PUT_request1.status[:3], '200')

        self.assertEqual(Place.get(Place.id == 1).name, 'foo-name2')
        self.assertEqual(
            Place.get(Place.id == 1).description, 'foo description 2')
        self.assertEqual(Place.get(Place.id == 1).number_rooms, 2)
        self.assertEqual(Place.get(Place.id == 1).number_bathrooms, 2)
        self.assertEqual(Place.get(Place.id == 1).max_guest, 2)
        self.assertEqual(Place.get(Place.id == 1).price_by_night, 2)
        self.assertEqual(Place.get(Place.id == 1).latitude, 30.0)
        self.assertEqual(Place.get(Place.id == 1).longitude, 32.0)

        # test response of PUT request for place by place id which does not exist
        PUT_request2 = self.app.put('/places/1000')
        self.assertEqual(PUT_request2.status[:3], '404')
示例#30
0
def place(place_id):
    if request.method == 'GET':
        try:
            new_place = Place.get(Place.id == place_id)
            return new_place.to_hash()
        except:
            return {'code':404, "msg":"not found"}, 404
    else:
        try:
            query = Place.get(Place.id == place_id)
        except:
            return {'code':404, "msg":"user does not exist"}, 404
        out_dict = query.to_hash()
        query.delete_instance()
        return out_dict
示例#31
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)
示例#32
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"
示例#33
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
示例#34
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)
示例#35
0
def create_place_by_city(state_id, city_id):
    """
    Create a place with id as place_id and state with  id as state_id
    """
    data = request.form
    try:
        if 'owner_id' not in data:
            raise KeyError('owner_id')
        if 'name' not in data:
            raise KeyError('name')

        city = City.get(City.id == city_id, City.state == state_id)
        new = Place.create(
            owner=data['owner_id'],
            name=data['name'],
            city=city.id,
            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']
        )
        res = {}
        res['code'] = 201
        res['msg'] = "Place was created successfully"
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
示例#36
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
示例#37
0
def put_place(place_id):
    post_data = request.values
    try:
        place = Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return {"code":404, "msg":"not found"}, 404
    
    if 'name' in post_data:
        place.name = post_data['name']
    if 'description' in post_data:
        place.description = post_data['description']
    if 'number_rooms' in post_data:
        place.number_rooms = int(post_data['number_rooms'])
    if 'number_bathrooms' in post_data:
        place.number_bathrooms = int(post_data['number_bathrooms'])
    if 'max_guest' in post_data:
        place.max_guest = int(post_data['max_guest'])
    if 'price_by_night' in post_data:
        place.price_by_night = int(post_data['price_by_night'])
    if 'latitude' in post_data:
        place.latitude = float(post_data['latitude'])
    if 'longitude' in post_data:
        place.longitude = float(post_data['longitude'])
    place.save()
    return place.to_dict()
示例#38
0
def create_place_by_city(state_id, city_id):
    post_data = request.values
    keys=["name", "description", "latitude", "longitude", "owner_id"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"bad request, incorrect parameters"}
    try:
       city = City.get(City.id == city_id, City.state == state_id)
    except:
        return {"code":400, "msg":"bad request, city or state does not exist"}, 400

    new_place = Place.create(
        owner=int(post_data['owner_id']),
        name=post_data['name'],
        city=city.id,
        description=post_data['description'],
        latitude=float(post_data['latitude']),
        longitude=float(post_data['longitude'])
    )
    if 'number_rooms' in post_data:
        new_place.number_rooms=int(post_data['number_rooms'])
    if 'number_bathrooms' in post_data:
        new_place.number_bathrooms=int(post_data['number_bathrooms'])
    if 'max_guest' in post_data:
        new_place.max_guest=int(post_data['max_guest'])
    if 'price_by_night' in post_data:
        new_place.price_by_night=int(post_data['price_by_night'])
    new_place.save()
    return new_place.to_hash()
示例#39
0
def create_place_by_city(state_id, city_id):
    post_data = request.values
    keys=["name", "description", "latitude", "longitude", "owner_id"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"bad request, incorrect parameters"}

    try:
        city = City.get(City.id == city_id, City.state == state_id)
    except City.DoesNotExist:
        return {"code":400, "msg":"bad request, city or state does not exist"}, 400

    place_dictionary = place_dict(
        post_data['name'],
        post_data['description'],
        post_data.get('number_rooms'),
        post_data.get('number_bathrooms'),
        post_data.get('max_guest'),
        post_data.get('price_by_night'),
        post_data['latitude'],
        post_data['longitude'],
        post_data['owner_id'],
        city.id,       
    )
    try:
        new_place = Place.create(**place_dictionary)
    except:
        return {"code":400, "msg":"Bad Request"}, 400

    return new_place.to_dict()
示例#40
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")
示例#41
0
def get_place(id):
    try:
        place = Place.get(Place.id == id)
    except Exception:
        return {'code': 404, 'msg': 'Place not found'}, 404

    return place.to_hash(), 200
示例#42
0
def put_place(place_id):
    post_data = request.values
    try:
        place = Place.get(Place.id == place_id)
    except:
        return {"code":404, "msg":"not found"}, 404
    try:
        for key in post_data:
            if key == 'name':
                place.name = post_data[key]
            if key == 'description':
                place.description = post_data[key]
            if key == 'number_rooms':
                place.number_rooms = int(post_data[key])
            if key == 'number_bathrooms':
                place.number_bathrooms = int(post_data[key])
            if key == 'max_guest':
                place.max_guest = int(post_data[key])
            if key == 'price_by_night':
                place.price_by_night = int(post_data[key])
            if key == 'latitude':
                place.latitude = float(post_data[key])
            if key == 'longitude':
                place.longitude = float(post_data[key])
        place.save()
        return place.to_hash()
    except:
        return {"code":404, "msg":"not found"}, 404
示例#43
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)
示例#44
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
示例#45
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)
示例#46
0
def delete_single_place(place_id):
    try:
        query = Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return {'code':404, "msg":"place does not exist"}, 404
    out_dict = query.to_dict()
    query.delete_instance()
    return out_dict
示例#47
0
def delete_place(id):
    try:
        place = Place.get(Place.id == id)
    except Exception:
        return {'code': 404, 'msg': 'Place not found'}, 404

    place.delete_instance()
    return {'code': 200, 'msg': 'Deleted successfully'}, 200
示例#48
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)
示例#49
0
def place_reviews(place_id):
    """Handle GET and POST requests to /places/<place_id>/reviews route.

    Return a list of all reviews for given place in the database in the case of
    a GET request.
    Create a new place review in the database in the case of a POST request.
    """
    # check whether place resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Place.get(Place.id == place_id)

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

    # if exception does not arise:
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = []
        for record in ReviewPlace.select().where(ReviewPlace.place == place_id):
            hash = record.review.to_hash()
            list.append(hash)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':

        if "stars" in request.form.keys():
            record = Review(
                message=request.form["message"],
                user=request.form["user_id"],
                stars=request.form["stars"]
            )

        else:
            record = Review(
                message=request.form["message"],
                user=request.form["user_id"]
            )

        record.save()

        p_review = ReviewPlace(
            place=place_id,
            review=record.id
        )
        p_review.save()

        return jsonify(record.to_hash())
示例#50
0
def get_place(place_id):
    """
    Get a place with id as place_id
    """
    try:
        place = Place.get(Place.id == place_id)
    except Exception:
        return {'code': 404, 'msg': 'Place not found'}, 404
    return place.to_dict(), 200
示例#51
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())
示例#52
0
def find_booking(place_id, book_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

    # Checking if the booking exist
    try:
        PlaceBook.get(PlaceBook.id == book_id)
    except PlaceBook.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Booking not found'}), 404
    # Find a booking
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id and
                                PlaceBook.place == place_id)
        return jsonify(booking.to_dict())
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
示例#53
0
    def createPlaceViaPeewee(self):
        """
        Create a place record using the API's database/Peewee models.

        createPlaceViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = Place(owner_id=1,
                       city_id=1,
                       name="foo",
                       description="foo description",
                       number_rooms=1,
                       number_bathrooms=1,
                       max_guest=1,
                       price_by_night=1,
                       latitude=20.0,
                       longitude=22.0)
        record.save()
        return record
示例#54
0
    def setUp(self):
        """
        Overload def setUp(self): to create a test client of airbnb app, and
        create placebook table in airbnb_test database.
        """
        self.app = app.test_client()  # set up test client
        self.app.testing = True  # set testing to True
        logging.disable(logging.CRITICAL)  # disable logs

        # connect to airbnb_test database and create tables
        database.connect()
        database.create_tables([User, State, City, Place, PlaceBook],
                               safe=True)

        # create user record for route
        user_record = User(email='anystring',
                           password='******',
                           first_name='anystring2',
                           last_name='anystring3')
        user_record.save()

        # create state record for route
        state_record = State(name="foo-state")
        state_record.save()

        # create city record for route
        city_record = City(name="foo-city", state="1")
        city_record.save()

        # create place records for route
        place_record = Place(owner=1,
                             city=1,
                             name="foo",
                             description="foo description",
                             number_rooms=1,
                             number_bathrooms=1,
                             max_guest=1,
                             price_by_night=1,
                             latitude=20.0,
                             longitude=22.0)
        place_record.save()

        place_record2 = Place(owner=1,
                              city=1,
                              name="foo",
                              description="foo description",
                              number_rooms=1,
                              number_bathrooms=1,
                              max_guest=1,
                              price_by_night=1,
                              latitude=20.0,
                              longitude=22.0)
        place_record2.save()
示例#55
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)
示例#56
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