示例#1
0
def handle_books_id(place_id, book_id):
    '''Returns a JSON object of the book_id with a GET request method. Updates
    a booking's attributes with a POST request method. Removes a booking with a
    DELETE request method.

    Keyword arguments:
    place_id: The id of the place with the booking.
    book_id: The id of the booking.
    '''
    try:
        book = PlaceBook.select().where(PlaceBook.id == book_id).get()
    except PlaceBook.DoesNotExist:
        raise Exception("There is no placebook with this id.")

    if request.method == 'GET':
        return jsonify(book.to_dict()), 200

    elif request.method == 'PUT':
        params = request.values
        for key in params:
            if key == 'user':
                return jsonify(msg="You may not change the user."), 409
            if key == 'updated_at' or key == 'created_at':
                continue
            setattr(book, key, params.get(key))
        book.save()
        return jsonify(msg="Place book information updated successfully."), 200

    elif request.method == 'DELETE':
        try:
            book = PlaceBook.delete().where(PlaceBook.id == book_id)
        except PlaceBook.DoesNotExist:
            raise Exception("There is no place with this id.")
        book.execute()
        return jsonify(msg="Place book deleted successfully."), 200
示例#2
0
def book_place(place_id):
    post_data = request.values
    keys=["user_id", "date_start"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"bad request"}, 404

    place_book_dictionary = placebook_dict(
        place_id,
        post_data['user_id'],
        post_data.get('is_validated'),
        post_data['date_start'],
        post_data.get('number_nights')
    )
    # check overlap
    query = PlaceBook.select().where(PlaceBook.place == place_id)
    new_book_end = place_book_dictionary['date_start'] + timedelta(days = place_book_dictionary['number_nights'])
    
    for booking in query:
        end_date = booking.date_start + timedelta(days=booking.number_nights)
        if  place_book_dictionary['date_start'].date() <= booking.date_start.date() <= new_book_end.date() or place_book_dictionary['date_start'].date() <= end_date.date() <= new_book_end.date():
            return {'code': 110000, 'msg': "Place unavailable at this date"}, 410
    # overlap check end

    new_book, created = PlaceBook.create_or_get(**place_book_dictionary)
    if not created:
        return {"code":400, "msg":"bad request"}, 404
    return new_book.to_dict()
示例#3
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()
def app_books_id(place_id, book_id):
    if request.method == "GET":
        try:
            query = PlaceBook.get(PlaceBook.id == book_id)
            return jsonify(query.to_dict()), 200
            
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
    
    elif request.method == "PUT":
        try:
            query = PlaceBook.get(PlaceBook.id == book_id)
            [setattr(query, key, value) for (key, value) in request.form.items() if key != "updated_at" and key != "created_at"]
            query.save()
            return jsonify(query.to_dict()), 200

        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "DELETE":
        try:
            query = PlaceBook.get(PlaceBook.id == book_id)
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200 

        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
示例#5
0
 def tearDown(self):
     #delete all from users
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
示例#6
0
def books(place_id):
    """Handle GET and POST requests to /places/<place_id>/books route.

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

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = PlaceBook(
            place=request.form['place'],
            user=request.form['user'],
            is_validated=request.form['is_validated'],
            date_start=datetime.strptime(
                request.form['date_start'],
                '%d/%m/%Y %H:%M:%S'
                ),
            number_nights=request.form['number_nights']
        )
        record.save()
        return jsonify(record.to_hash())
示例#7
0
def view_create_delete(place_id, book_id):
    bookings = PlaceBook.select().where(PlaceBook.place == place_id).where(
        PlaceBook.id == book_id).first()

    if request.method == 'GET':
        return jsonify(bookings.to_hash())

    elif request.method == 'PUT':
        booking_info = request.values
        for key in booking_info:
            '''Sustained by MySQL'''
            if key == 'place':
                bookings.place = booking_info.get(key)
            if key == 'user':
                return jsonify(msg="User cannot be changed")
            if key == 'is_validated':
                bookings.is_validated = booking_info.get(key)
            if key == 'date_start':
                bookings.date_start = booking_info.get(key)
            if key == 'number_nights':
                bookings.number_nights = booking_info.get(key)

        bookings.save()
        return jsonify(bookings.to_hash())

    elif request.method == 'DELETE':
        booking_info = PlaceBook.select().where(
            PlaceBook.place == place_id).where(
                PlaceBook.id == book_id).first()
        booking_info.delete_instance()
        place_info.save()
        return jsonify(msg='Booking deleted')
示例#8
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
示例#9
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)
示例#10
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()
示例#11
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()
示例#12
0
def create_books(id):
    data = request.form
    book = PlaceBook()
    book.place = id
    for entry in data:
        if entry == 'date_start':
            setattr(book, entry, datetime.strptime(data[entry], '%Y/%m/%d %H:%M:%S'))
        else:
            setattr(book, entry, data[entry])

    book.save()
    return {'code': 201, 'msg': 'Book created successfully'}, 201
示例#13
0
def book_date(place_id):
    """
    Create a booking with id as place_id
    """
    data = request.form
    try:
        if 'user_id' not in data:
            raise KeyError('user_id')
        elif 'date_start' not in data:
            raise KeyError('date_start')
        book_start = datetime.strptime(
            data['date_start'], "%Y/%m/%d %H:%M:%S").replace(hour=0, minute=0, second=0)
        book_end = book_start + timedelta(days=int(data['number_nights']))
        bookings = PlaceBook.select().where(PlaceBook.place == place_id)
        for booking in bookings:
            date_start = booking.date_start.replace(hour=0, minute=0, second=0)
            date_end = date_start + timedelta(days=int(booking.number_nights))
            if book_start >= date_start and book_start < date_end:
                raise ValueError('booked')
            elif book_end > date_start and book_end <= date_end:
                raise ValueError('booked')
            elif date_start >= book_start and date_start < book_end:
                raise ValueError('booked')

        new = PlaceBook.create(
            place=place_id,
            user=data['user_id'],
            is_validated=data['is_validated'],
            date_start=datetime.strptime(
                data['date_start'], "%Y/%m/%d %H:%M:%S"),
            number_nights=data['number_nights']
        )
        res = {}
        res['code'] = 201
        res['msg'] = "Booking was created successfully"
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
    except ValueError as e:
        if e.message == 'booked':
            res = {}
            res['code'] = 110000
            res['msg'] = 'Place unavailable at this date'
            return res, 410
    except Exception as error:
        res = {}
        res['code'] = 403
        res['msg'] = str(error)
        return res, 403
示例#14
0
    def createPlaceBookViaPeewee(self):
        """
        Create a placebook record using the API's database/Peewee models.

        createPlaceBookViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = PlaceBook(     user_id=1,
                                is_validated=False,
                                date_start=datetime.now().strftime('%d/%m/%Y %H:%M:%S'),
                                number_nights=1 )
        record.save()
        return record
示例#15
0
    def createPlaceBookViaPeewee(self):
        """
        Create a placebook record using the API's database/Peewee models.

        createPlaceBookViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = PlaceBook(
            user_id=1,
            is_validated=False,
            date_start=datetime.now().strftime('%d/%m/%Y %H:%M:%S'),
            number_nights=1)
        record.save()
        return record
示例#16
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"
示例#17
0
def delete_booking(place_id, book_id):
    """
    Delete booking with id as place_id
    """
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id)
    except Exception:
        return {'code': 404, 'msg': 'Booking not found'}, 404
    booking = PlaceBook.delete().where(PlaceBook.id == book_id)
    booking.execute()
    response = {}
    response['code'] = 200
    response['msg'] = "Booking was deleted successfully"
    return response, 200
示例#18
0
    def subtest_createWithAllParams(self):
        """
        Test proper creation of a placebook record upon POST request to the API
        with all parameters provided.
        """
        POST_request1 = self.createPlaceBookViaAPI()
        self.assertEqual(POST_request1.status[:3], '200')

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

        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).place_id, 1)
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).user_id, 1)
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).is_validated, False)
        self.assertEqual(
            PlaceBook.get(PlaceBook.id == 1).date_start,
            datetime.now().strftime('%d/%m/%Y %H:%M'))
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).number_nights, 1)
        self.assertEqual(
            PlaceBook.get(
                PlaceBook.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        self.assertEqual(
            PlaceBook.get(
                PlaceBook.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test that placebook ID for sole record in database is correct
        self.assertEqual(PlaceBook.select().get().id, 1)
示例#19
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")
示例#20
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")
示例#21
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
示例#22
0
def get_book(pid, id):
    try:
        book = PlaceBook.get(PlaceBook.id == id, PlaceBook.place_id == pid)
    except Exception:
        return {'code': 404, 'msg': 'Book not found'}, 404

    return book.to_hash(), 200
示例#23
0
def check_places_availability(place_id):
    post_data = request.values
    
    keys = ['year', 'month', 'day']
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"Bad Request"}, 400
    
    query = PlaceBook.select().where(PlaceBook.place == place_id)
    if not query.exists():
        return {"code":400, "msg":"Bad Request, place does not exist"}, 400
    
    date_req = "%s/%s/%s" % (post_data['year'], post_data['month'], post_data['day'])
    dt = datetime.strptime(date_req, "%Y/%m/%d").date()
    
    for booking in query:
        end_date = booking.date_start.date() + timedelta(days=booking.number_nights)
        if booking.date_start.date() <= dt <= end_date:
            available = False
            break
        else:
            available = True
    
    return {
        "available": available
    }
    
示例#24
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)
示例#25
0
def update_booking(place_id, book_id):
    """
    Update the booking details of booking with id as place_id
    """
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id)
        data = request.form
        for key in data:
            if key == 'user_id':
                raise Exception('User cannot be changed')
            elif key == 'is_validated':
                booking.is_validated = data[key]
            elif key == 'date_start':
                booking.date_start = datetime.strptime(
                    data[key], "%Y/%m/%d %H:%M:%S")
            elif key == 'number_nights':
                booking.number_nights = data[key]
        booking.save()
        res = {}
        res['code'] = 200
        res['msg'] = "Booking was updated successfully"
        return res, 200
    except Exception as error:
        res = {}
        res['code'] = 403
        res['msg'] = str(error)
        return res, 403
示例#26
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
示例#27
0
def del_book(place_id, book_id):
    try:
        query = PlaceBook.get(PlaceBook.id == book_id)
    except:
        return {"code":404, "msg":"not found"}, 404
    out_dict = query.to_hash()
    query.delete_instance()
    return out_dict
示例#28
0
def del_single_book(place_id, book_id):
    try:
        query = PlaceBook.get(PlaceBook.id == book_id)
    except PlaceBook.DoesNotExist:
        return {"code":404, "msg":"not found"}, 404
    out_dict = query.to_dict()
    query.delete_instance()
    return out_dict
示例#29
0
def delete_book(pid, id):
    try:
        book = PlaceBook.get(PlaceBook.id == id, PlaceBook.place_id == pid)
    except Exception:
        return {'code': 404, 'msg': 'Book not found'}, 404

    book.delete_instance()
    return {'code':200, 'msg': 'Deleted successfully'}, 200
示例#30
0
def states(place_id):
    if request.method == 'GET':
        books_list = []
        books = PlaceBook.select().join(Place).where(Place.id == place_id)
        for book in books:
            books_list.append(book.to_hash())
        return jsonify(books_list)

    elif request.method == 'POST':
        new_book = PlaceBook.create(
            place=request.form['place'],
            user=request.form['user'],
            is_validated=request.form['is_validated'],
            date_start=request.form['date_start'],
            number_nights=request.form['number_nights'],
        )
        return jsonify(new_book.to_hash())
示例#31
0
def get_book_by_id(place_id, book_id):
    books = PlaceBook.select().where(PlaceBook.id == int(book_id))
    book = None
    for u in books:
        book = u
    if book == None:
        return "Failed"
    return jsonify(book.to_hash())
示例#32
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())
示例#33
0
def get_place_books(place_id):
    try:
        query = PlaceBook.select().where(PlaceBook.place == place_id)
    except:
        return {"code":404, "msg":"not found"}, 404
    place_books = []
    for place_book in query:
        place_books.append(place_book.to_hash())
    return jsonify(place_books)
示例#34
0
def view_create_placebook(place_id):
    if request.method == 'GET':
        place = PlaceBook.select().where(PlaceBook.place == place_id)

        if place:
            order_values = [i.to_hash() for i in place]
            return jsonify(order_values)

        else:
            return jsonify(msg="There are no bookings for this place."), 404

    elif request.method == 'POST':
        place = PlaceBook.create(place=place_id,
                                 user=request.form['user'],
                                 is_validated=request.form['is_validated'],
                                 date_start=request.form['date_start'],
                                 number_nights=request.form['number_nights'])
        return jsonify(place.to_hash())
示例#35
0
def get_booking(place_id, book_id):
    """
    Get a booking with id as place_id
    """
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id)
    except Exception:
        return {'code': 404, 'msg': 'Booking not found'}, 404
    return booking.to_dict(), 200
示例#36
0
def get_all_bookings(place_id):
    """
    Get all bookings for a place
    Get all bookings for a place
    ---
    tags:
      - booking
    responses:
      200:
        description: List of all bookings at a place
        schema:
          id: bookings_array
          properties:
            bookings:
              type: array
              description: bookings array
              items:
                properties:
                    place_id:
                        type: number
                        description: id of the place for a booking
                        default: 0
                    user_id:
                        type: number
                        description: id of the user who booked the place
                        default: 0
                    is_validated:
                        type: boolean
                        description: true if the booking has been validated
                        default: false
                    date_start:
                        type: datetime string
                        description: the date of the booking
                        default: '2016-08-11 20:30:38.959846'
                    number_nights:
                        type: number
                        description: duration of the booking
                        default: 1
                    id:
                        type: number
                        description: id of the amenity
                        default: 0
                    created_at:
                        type: datetime string
                        description: date and time the amenity was created
                        default: '2016-08-11 20:30:38.959846'
                    updated_at:
                        type: datetime string
                        description: date and time the amenity was updated
                        default: '2016-08-11 20:30:38.959846'
              default: [{"place_id": 0, "user_id": 0, "is_validated": false, "date_start": "2016-08-11 20:30:38.959846", "number_nights": 4, "id": 0, "created_at": "2016-08-11 20:30:38.959846", "updated_at": "2016-08-11 20:30:38.959846"}, {"place_id": 0, "user_id": 0, "is_validated": false, "date_start": "2016-08-16 20:30:38.959846", "number_nights": 4, "id": 0, "created_at": "2016-08-11 20:30:38.959846", "updated_at": "2016-08-11 20:30:38.959846"}]
    """
    books = []
    for book in PlaceBook.select().where(PlaceBook.place == place_id):
        books.append(book.to_dict())
    return jsonify({"books": books})
示例#37
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
示例#38
0
def delete_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
    # Delete a booking
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id and
                                PlaceBook.place == place_id)
        booking.delete_instance()
        return jsonify({'msg': 'Booked place was deleted'}), 200
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
示例#39
0
def get_book_by_id(place_id, book_id):
    """
    Details about one booking
    Get details about one booking
    ---
    tags:
      - booking
    responses:
      200:
        description: Details about one booking
        schema:
          id: booking
          properties:
            place_id:
                type: number
                description: id of the place for a booking
                default: 0
            user_id:
                type: number
                description: id of the user who booked the place
                default: 0
            is_validated:
                type: boolean
                description: true if the booking has been validated
                default: false
            date_start:
                type: datetime string
                description: the date of the booking
                default: '2016-08-11 20:30:38.959846'
            number_nights:
                type: number
                description: duration of the booking
                default: 1
            id:
                type: number
                description: id of the amenity
                default: 0
            created_at:
                type: datetime string
                description: date and time the amenity was created
                default: '2016-08-11 20:30:38.959846'
            updated_at:
                type: datetime string
                description: date and time the amenity was updated
                default: '2016-08-11 20:30:38.959846'
    """
    books = PlaceBook.select().where(PlaceBook.id == int(book_id))
    book = None
    for u in books:
        book = u
    if book == None:
        return error_msg(400, 400, "Error")
    return jsonify(book.to_dict())
示例#40
0
def books(place_id):
    """Handle GET and POST requests to /places/<place_id>/books route.

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

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        record = PlaceBook(place=request.form['place'],
                           user=request.form['user'],
                           is_validated=request.form['is_validated'],
                           date_start=datetime.strptime(
                               request.form['date_start'],
                               '%d/%m/%Y %H:%M:%S'),
                           number_nights=request.form['number_nights'])
        record.save()
        return jsonify(record.to_hash())
示例#41
0
    def test_update(self):
        """
        Test update of place_book records upon PUT requests to API.
        """
        self.createPlaceBookViaPeewee()

        PUT_request1 = self.app.put('places/1/books/1', data=dict(
            place_id=2,
            is_validated=True,
            date_start=datetime.now().strftime('%d/%m/%Y %H:%M:%S'),
            number_nights=3
        ))
        self.assertEqual(PUT_request1.status[:3], '200')

        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).place_id, 2)
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).is_validated, True)
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).date_start, datetime.now().strftime('%d/%m/%Y %H:%M'))
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).number_nights, 3)

        # test response of PUT request for user by user id which does not exist
        PUT_request2 = self.app.put('places/1/books/1000')
        self.assertEqual(PUT_request2.status[:3], '404')
示例#42
0
    def test_update(self):
        """
        Test update of place_book records upon PUT requests to API.
        """
        self.createPlaceBookViaPeewee()

        PUT_request1 = self.app.put(
            'places/1/books/1',
            data=dict(place_id=2,
                      is_validated=True,
                      date_start=datetime.now().strftime('%d/%m/%Y %H:%M:%S'),
                      number_nights=3))
        self.assertEqual(PUT_request1.status[:3], '200')

        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).place_id, 2)
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).is_validated, True)
        self.assertEqual(
            PlaceBook.get(PlaceBook.id == 1).date_start,
            datetime.now().strftime('%d/%m/%Y %H:%M'))
        self.assertEqual(PlaceBook.get(PlaceBook.id == 1).number_nights, 3)

        # test response of PUT request for user by user id which does not exist
        PUT_request2 = self.app.put('places/1/books/1000')
        self.assertEqual(PUT_request2.status[:3], '404')
示例#43
0
def app_books(place_id):
    if request.method == "GET":
        try:
            query = PlaceBook.select().where(PlaceBook.place == place_id)
            if not query.exists():
                raise Exception
            return ListStyles.list(query, request), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "POST":
        try:
            dt_start = datetime.datetime.strptime(request.form['date_start'], '%Y/%m/%d %H:%M:%S')
        except ValueError:
            return jsonify({"code": 400, "msg": "improper date format"}), 400

        dt_end = dt_start + datetime.timedelta(days=int(request.form.get('number_nights', 1)))
        list_place_bookings = PlaceBook.select().where(PlaceBook.place == place_id)

        for booking in list_place_bookings:
            start_date = datetime.datetime.strptime(booking.date_start.strftime("%Y%m%d"), "%Y%m%d")
            end_date = start_date + datetime.timedelta(days=booking.number_nights)
            if (end_date >= dt_start >= start_date) or (end_date >= dt_end >= start_date):
                return jsonify({'code': 110000, 'msg': "Place unavailable at this date"}), 410
            
        try:
            new = PlaceBook.create(
                place=int(place_id),
                user=int(request.form['user']),
                date_start=dt_start,
                number_nights=int(request.form.get('number_nights', 1))
            )
            return jsonify(new.to_dict()), 200

        except:
            return jsonify({"code": 10006, "msg": "Booking error: place or user may not yet exist"}), 409
示例#44
0
def book_id(place_id, book_id):
    """Handle GET, PUT & DELETE requests to /places/<place_id>/books/<book_id>.

    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 = PlaceBook.get(PlaceBook.id == book_id)

    except PlaceBook.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':
        return jsonify(record.to_hash())

    # handle PUT requests
    elif request.method == 'PUT':
        # code below can be optimized in future using list comprehensions
        for key in request.values.keys():
            if key == "place":
                record.place = request.values[key]
            elif key == "user":
                record.user = request.values[key]
            elif key == "is_validated":
                record.is_validated = request.values[key]
            elif key == "date_start":
                record.date_start = request.values[key]
            elif key == "number_nights":
                record.number_nights = request.values[key]
            record.save()
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted booking\n'
示例#45
0
def handle_books(place_id):
    '''Returns all bookings as JSON objects in an array with a GET
    request. Adds a booking to the place_id with a POST request.

    Keyword arguments:
    place_id: The id of the place with the booking.
    '''
    if request.method == 'GET':
        list = ListStyle().list(
            (PlaceBook.select().where(PlaceBook.place == place_id)), request)
        return jsonify(list), 200

    elif request.method == 'POST':
        try:
            datetime.strptime(request.form['date_start'], "%Y/%m/%d %H:%M:%S")
        except ValueError:
            return jsonify(msg="Incorrect time format: should be " +
                           "yyyy/MM/dd HH:mm:ss"), 409
        '''Convert the date_start into a date without time.'''
        book_inquiry = datetime.strptime(request.form['date_start'],
                                         "%Y/%m/%d %H:%M:%S").date()

        arr = []
        for place_book in (PlaceBook.select().where(
                PlaceBook.place == place_id).iterator()):
            start = place_book.date_start.date()
            end = start + timedelta(days=place_book.number_nights)
            '''Check to see if book_inquiry date is not taken.'''
            if book_inquiry >= start and book_inquiry < end:
                return jsonify(available=False), 200

        params = request.values
        book = PlaceBook()
        '''Check that all the required parameters are made in request.'''
        required = set(["date_start", "user"]) <= set(request.values.keys())
        if required is False:
            return jsonify(msg="Missing parameter."), 400

        for key in params:
            if key == 'updated_at' or key == 'created_at':
                continue
            setattr(book, key, params.get(key))
        book.place = place_id
        book.save()
        return jsonify(book.to_dict()), 200
示例#46
0
def delete_book_by_id(place_id, book_id):
    """
    Delete a booking
    Deletes a booking based on id.
    ---
    tags:
      - booking
    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:
        books = PlaceBook.select().where(PlaceBook.id == int(book_id))
        book = None
        for u in books:
            book = u
        if book == None:
            return error_msg(400, 400, "Error")
        book.delete_instance()
    except:
        return error_msg(400, 400, "Error")
    return error_msg(200, 200, "Success")
示例#47
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)
示例#48
0
def book_id(place_id, book_id):
    """Handle GET, PUT & DELETE requests to /places/<place_id>/books/<book_id>.

    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 = PlaceBook.get(PlaceBook.id == book_id)

    except PlaceBook.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':
        return jsonify(record.to_hash())

    # handle PUT requests
    elif request.method == 'PUT':
        # code below can be optimized in future using list comprehensions
        for key in request.values.keys():
            if key == "place":
                record.place = request.values[key]
            elif key == "user":
                record.user = request.values[key]
            elif key == "is_validated":
                record.is_validated = request.values[key]
            elif key == "date_start":
                record.date_start = request.values[key]
            elif key == "number_nights":
                record.number_nights = request.values[key]
            record.save()
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted booking\n'
示例#49
0
def modify_booking(place_id, book_id):
    # Modify a booking
    try:
        booking = PlaceBook.get(PlaceBook.id == book_id)
        data = request.form
        for key in data:
            if key == 'user_id':
                return jsonify({'code': 405, 'msg': 'Method not allowed'}), 405
            elif key == 'date_start':
                booking.date_start = data[key]
            elif key == '`number_nights`':
                booking.number_nights = data[key]
            elif key == 'is_validated':
                booking.is_validated = data[key]
            booking.save()
        return jsonify(booking.to_dict())
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
示例#50
0
def check_availability(place_id):
    try:
        year = request.form['year']
        month = request.form['month']
        day = request.form['day']
    except KeyError:
        return jsonify({'code': 409, 'msg': "Form data must contain 'year', 'month', and 'day' to check availability"}), 409

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

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

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

    return jsonify({'available': True}), 200
示例#51
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
示例#52
0
def get_place_bookings(place_id):
    """
    Get all bookings with id as place_id
    """
    data = PlaceBook.select().where(PlaceBook.place == place_id)
    return ListStyle.list(data, request), 200
示例#53
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
示例#54
0
            user=request.form['user'],
            is_validated=request.form['is_validated'],
            date_start=request.form['date_start'],
            number_nights=request.form['number_nights'],
        )
        return jsonify(new_book.to_hash())

@app.route('/places/<place_id>/books/<book_id>', methods=['GET', 'PUT', 'DELETE'])
def book_id(place_id, book_id):))
    if request.method == 'GET':
        book = Book.get(PlaceBook.id == book_id, PlaceBook.place == place_id)
        return jsonify(book.to_hash())

    if request.method == 'PUT':
        try:
            update_book = PlaceBook.update(place=request.form['place']).where(PlaceBook.place == place_id, PlaceBook.id == book_id)
            update_book.execute()
        except:
            pass
        try:
            update_book = PlaceBook.update(is_validated=request.form['is_validated']).where(PlaceBook.place == place_id, PlaceBook.id == book_id)
            update_book.execute()
        except:
            pass
        try:
            update_book = PlaceBook.update(date_start=request.form['date_start']).where(PlaceBook.place == place_id, PlaceBook.id == book_id)
            update_book.execute()
        except:
            pass
        try:
            update_book = PlaceBook.update(number_nights=request.form['number_nights']).where(PlaceBook.place == place_id, PlaceBook.id == book_id)