Exemplo n.º 1
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)
Exemplo n.º 2
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)
Exemplo n.º 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())
Exemplo n.º 4
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
Exemplo n.º 5
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'
Exemplo n.º 6
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'
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
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')
Exemplo n.º 10
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')
Exemplo n.º 11
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
Exemplo n.º 12
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()
Exemplo n.º 13
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
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
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())
Exemplo n.º 18
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
Exemplo n.º 19
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
Exemplo n.º 20
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
Exemplo n.º 21
0
def list_put_delete():
    place = Place.get().where(Place.id == place_id)

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

    elif method == 'PUT':
        place_info = request.values
        for key in place_info:
            '''Sustained by MySQL'''
            if key == 'updated_at' or key == 'created_at' or key == 'id':
                continue
            if key == 'owner_id':
                place.owner_id = place_info.get(key)
            if key == 'city_id':
                place.city_id = place_info.get(key)
            if key == 'name':
                place.name = place_info.get(key)
            if key == 'description':
                place.description = place_info.get(key)
            if key == 'number_rooms':
                place.number_rooms = place_info.get(key)
            if key == 'number_bathrooms':
                place.number_bathrooms = place_info.get(key)
            if key == 'max_guest':
                place.max_guest = place_info.get(key)
            if key == 'price_by_night':
                place.price_by_night = place_info.get(key)
            if key == 'latitude':
                place.latitude = place_info.get(key)
            if key == 'longitude':
                place.longitude = place_info.get(key)

        user.save()
        return jsonify(place.to_hash())

    elif method == 'DELETE':
        place_info = Place.get().where(Place.id == place_id)
        place_info.delete_instance()
        place_info.save()
        return jsonify(msg='Place deleted')
Exemplo n.º 22
0
def review_place_id(place_id, review_id):
    """Handle GET and DELETE requests to /places/<place_id>/reviews/<review_id>.

    Return a hash representing place review in the case of a GET request.
    Delete appropriate records for place review in case of DELETE 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:

    # check whether review resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Review.get(Review.id == review_id)

    # return 404 not found if it does not
    except Review.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 DELETE requests
    elif request.method == "DELETE":
        pr_record = ReviewPlace.get(ReviewPlace.review == review_id)
        pr_record.delete_instance()
        pr_record.save()
        record.delete_instance()
        record.save()
        return 'deleted review record\ndeleted review place record\n'
Exemplo n.º 23
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
Exemplo n.º 24
0
def update(place_id, amenity_id):
    # Checking if place exist
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Place not found'}), 404

    # Checking is Amenity exist
    try:
        Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Amenity not found'}), 404

    if request.method == "POST":
        new_place_amenity = PlaceAmenities(place=place_id, amenity=amenity_id)
        new_place_amenity.save()
        return jsonify(new_place_amenity.amenity.to_dict())

    elif request.method == "DELETE":
        get_place_a = PlaceAmenities.get(PlaceAmenities.place == place_id and
                                         PlaceAmenities.amenity == amenity_id)
        get_place_a.delete_instance
        return "amenity deleted"
Exemplo n.º 25
0
def update(place_id, amenity_id):
    # Checking if place exist
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Place not found'}), 404

    # Checking is Amenity exist
    try:
        Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Amenity not found'}), 404

    if request.method == "POST":
        new_place_amenity = PlaceAmenities(place=place_id, amenity=amenity_id)
        new_place_amenity.save()
        return jsonify(new_place_amenity.amenity.to_dict())

    elif request.method == "DELETE":
        get_place_a = PlaceAmenities.get(
            PlaceAmenities.place == place_id
            and PlaceAmenities.amenity == amenity_id)
        get_place_a.delete_instance
        return "amenity deleted"
Exemplo n.º 26
0
def app_places_id(place_id):
    if request.method == "GET":
        try:
            query = Place.get(Place.id == place_id)
            return jsonify(query.to_dict()), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "PUT":
        try:
            query = Place.get(Place.id == place_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 = Place.get(Place.id == place_id)
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Exemplo n.º 27
0
 def test_createByCity(self):
     """
     test_createByCity tests proper creation of a place record by city upon
     POST request to API
     """
     POST_request = self.app.post('/states/1/cities/1/places',
                                  data=dict(owner_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))
     self.assertEqual(Place.get(Place.id == 1).city.id, 1)
Exemplo n.º 28
0
 def test_createByCity(self):
     """
     test_createByCity tests proper creation of a place record by city upon
     POST request to API
     """
     POST_request = self.app.post('/states/1/cities/1/places', data=dict(
         owner_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
     ))
     self.assertEqual(Place.get(Place.id == 1).city.id, 1)
Exemplo n.º 29
0
def update_place(id):
    data = request.form
    try:
        place = Place.get(Place.id == id)
    except Exception:
        return {'code': 404, 'msg': 'Place not found'}, 404

    for i in data:
        if i == 'owner' or i == 'city':
            switch = {
                'owner': 'owner_id',
                'city' : 'city_id'
            }.get(i)
            i = switch
        setattr(place, i, data[i])

    place.save()
    return {'code': 200, 'msg': 'Updated successfully'}, 200
Exemplo n.º 30
0
def post_review_by_place(place_id):
	post_data = request.values
	if 'message' not in post_data or 'user_id' not in post_data:
		return {"code": 400, "msg":"bad request, incomplete parameters"}, 400
	try:
		place_get = Place.get(Place.id == place_id)
	except Place.DoesNotExist:
		return {'code': 10004, 'msg': 'Place does not exist'}, 404
	review_dictionary = review_dict(
    	post_data['message'],
    	post_data['user_id'],
    	post_data.get('stars'),
    )

	new_review, created = Review.create_or_get(**review_dictionary)
	if not created:
		return {'code': 404, 'msg': 'User does not exist'}, 404
	new_review_place = ReviewPlace.create(place=place_id, review=new_review)
	return new_review.to_dict()
Exemplo n.º 31
0
def list_place_by_state():
    place_info = Place.get().where(Place.state == state_id).where(
        Place.city == city_id)

    if method == 'GET':
        jsonify(place_info.to_hash())

    elif 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())
Exemplo n.º 32
0
def update_place(place_id):
    """
    Update the place details of place with id as place_id
    """
    data = request.form
    try:
        place = Place.get(Place.id == place_id)
        for key in data:
            if key == 'owner':
                raise Exception('Owner cannot be changed')
            elif key == 'city':
                raise Exception('City cannot be changed')
            elif key == 'name':
                place.name = data[key]
            elif key == 'description':
                place.description = data[key]
            elif key == 'number_rooms':
                place.number_rooms = data[key]
            elif key == 'number_bathrooms':
                place.number_bathrooms = data[key]
            elif key == 'max_guest':
                place.max_guest = data[key]
            elif key == 'price_by_night':
                place.price_by_night = data[key]
            elif key == 'latitude':
                place.latitude = data[key]
            elif key == 'longitude':
                place.longitude = data[key]
        place.save()
        res = {}
        res['code'] = 200
        res['msg'] = "Place was updated successfully"
        return res, 200
    except Exception as error:
        res = {}
        res['code'] = 403
        res['msg'] = str(error)
        return res, 403
Exemplo n.º 33
0
def get_place(place_id):
    """
    Get the given place
    Returns the given place in the database.
    ---
    tags:
        - Place
    parameters:
        -
            in: path
            name: place_id
            type: integer
            required: True
            description: ID of the place
    responses:
        200:
            description: Place returned successfully
            schema:
                id: Place
                required:
                    - owner_id
                    - city_id
                    - name
                    - id
                    - created_at
                    - updated_at
                properties:
                    owner_id:
                        type: integer
                        description: user id of the owner
                        default: 1
                    city_id:
                        type: integer
                        description: id of the city
                        default: 1
                    name:
                        type: string
                        description: name of the place
                        default: 'Amazing view near San Francisco'
                    description:
                        type: string
                        description: description of the place
                        default: "The place is located on the ocean's edge... literally."
                    number_rooms:
                        type: integer
                        description: number of rooms
                        default: 3
                    number_bathrooms:
                        type: integer
                        description: number of bathrooms
                        default: 2
                    max_guest:
                        type: integer
                        description: the max number of guests
                        default: 6
                    price_by_night:
                        type: integer
                        description: the price per night of the location
                        default: 200
                    latitude:
                        type: float
                        description: the latitude of the place location
                        default: 37.642357
                    longitude:
                        type: float
                        description: the longitude of the place location
                        default: -122.493439
                    id:
                        type: integer
                        description: id of the place
                        default: 1
                    created_at:
                        type: datetime string
                        description: date and time the booking was created in the database
                        default: '2016-08-11 20:30:38'
                    updated_at:
                        type: datetime string
                        description: date and time the booking was updated in the database
                        default: '2016-08-11 20:30:38'
        404:
            description: Place, owner or city was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check if place_id exists '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Return place data '''
        place = Place.get(Place.id == place_id)
        return place.to_dict(), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Exemplo n.º 34
0
def update_place(place_id):
    """
    Update a place
    Update a place in the database
    ---
    tags:
        - Place
    parameters:
        -
            name: place_id
            in: path
            type: integer
            required: True
            description: ID of the place
        -
            name: name
            in: form
            type: string
            description: name of the place
        -
            name: description
            in: form
            type: string
            description: description of the place
        -
            name: number_rooms
            in: form
            type: integer
            description: number of rooms
        -
            name: number_bathrooms
            in: form
            type: integer
            description: number of bathrooms
        -
            name: max_guest
            in: form
            type: integer
            description: the max number of guests
        -
            name: price_by_night
            in: form
            type: integer
            description: the price per night of the location
        -
            name: latitude
            in: form
            type: float
            description: the latitude of the place location
        -
            name: longitude
            in: form
            type: float
            description: the longitude of the place location
    responses:
        200:
            description: Place was updated
            schema:
                $ref: '#/definitions/update_booking_put_put_success'
        400:
            description: Issue with booking update request
        404:
            description: Place was not found
        410:
            description: Place is unavailable for the requested booking
        500:
            description: The request was not able to be processed
    """
    try:
        data = {}
        for key in request.form.keys():
        	for value in request.form.getlist(key):
        		data[key] = value

        ''' Check if place_id exists '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Check that no request to change protected values '''
        if 'owner_id' in data:
            raise ValueError('Owner cannot be changed')
        if 'city_id' in data:
            raise ValueError('City cannot be changed')

        ''' Check for valid data types '''
        if 'name' in data and not type_test(data['name'], 'string'):
            raise TypeError('name is not a string')
        if 'description' in data and not type_test(data['description'], 'string'):
            raise TypeError('description is not a string')
        if 'number_rooms' in data and not type_test(data['number_rooms'], int):
            raise TypeError('number_rooms is not an integer')
        if 'number_bathrooms' in data and not type_test(data['number_bathrooms'], int):
            raise TypeError('number_bathrooms is not an integer')
        if 'max_guest' in data and not type_test(data['max_guest'], int):
            raise TypeError('max_guest is not an integer')
        if 'price_by_night' in data and not type_test(data['price_by_night'], int):
            raise TypeError('price_by_night is not an integer')
        if 'latitude' in data and not type_test(data['latitude'], float):
            raise TypeError('latitude is not a float')
        if 'longitude' in data and not type_test(data['longitude'], float):
            raise TypeError('longitude is not a float')

        place = Place.get(Place.id == place_id)
        for key in data:
            if key == 'name':
                place.name = data[key]
            elif key == 'description':
                place.description = data[key]
            elif key == 'number_rooms':
                place.number_rooms = data[key]
            elif key == 'number_bathrooms':
                place.number_bathrooms = data[key]
            elif key == 'max_guest':
                place.max_guest = data[key]
            elif key == 'price_by_night':
                place.price_by_night = data[key]
            elif key == 'latitude':
                place.latitude = data[key]
            elif key == 'longitude':
                place.longitude = data[key]
        place.save()
        res = {}
        res['code'] = 200
        res['msg'] = "Place was updated successfully"
        return res, 200
    except ValueError as e:
        res = {}
        res['code'] = 403
        res['msg'] = e.message
        return res, 403
    except LookupError as e:
        abort(404)
    except TypeError as e:
        res = {}
        res['code'] = 400
        res['msg'] = e.message
        return res, 400
    except Exception as error:
        abort(500)
Exemplo n.º 35
0
def get_single_place(place_id):
    try:
        new_place = Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return {'code':404, "msg":"not found"}, 404
    return new_place.to_dict()
Exemplo n.º 36
0
def place_id(place_id):
	if request.method == "GET":
		try:
			place = Place.get(Place.id == place_id)
			return jsonify(place.to_dict()), 200

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

	elif request.method == "PUT":
		try:
			place = Place.get(Place.id == place_id)

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

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

			elif key == "description":
				place.description = request.form[key]

			elif key == "number_rooms":
				place.number_rooms = request.form[key]

			elif key == "number_bathrooms":
				place.number_bathrooms = request.form[key]

			elif key == "max_guest":
				place.max_guest = request.form[key]

			elif key == "price_by_night":
				place.price_by_night = request.form[key]

			elif key == "latitude":
				place.latitude = request.form[key]

			elif key == "longitude":
				place.longitude = request.form[key]

			elif key == "owner_id":
				return json_response(status_=400, msg="Cant update owner id")

			elif key == "city":
				return json_response(status_=400, msg="Cant update city id")

		place.save()

		return jsonify(place.to_dict()), 200

	elif request.method == "DELETE":
		try:
			place = Place.get(Place.id == place_id)

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

		place.delete_instance()
		place.save()
		return json_response(status_=200, msg="Place deleted")
Exemplo n.º 37
0
def place_id(place_id):
    if request.method == 'GET':
        place = Place.get(Place.id == place_id)
        return jsonify(place.to_hash())

    if request.method == 'PUT':
        try:
            update_place = Place.update(name=request.form['name']).where(
                Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                description=request.form['description']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                number_rooms=request.form['number_rooms']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                number_bathrooms=request.form['number_bathrooms']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                max_guest=request.form['max_guest']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                price_by_night=request.form['price_by_night']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                latitude=request.form['latitude']).where(Place.id == place_id)
            update_place.execute()
        except:
            pass
        try:
            update_place = Place.update(
                longitude=request.form['longitude']).where(
                    Place.id == place_id)
            update_place.execute()
        except:
            pass
        updated_place = Place.get(Place.id == place_id)
        return jsonify(updated_place.to_hash())

    elif request.method == 'DELETE':
        place = Place.get(Place.id == place_id)
        place.delete_instance()
        return 'Place %s deleted \n' % place_id