Example #1
0
def get_place_amenities(place_id):
    """
    Get amenities for place
    Return a list of all amenities for a place
    ---
    tags:
        - Amenity
    parameters:
        -
            in: path
            name: place_id
            type: string
            required: True
            description: ID of the place
    responses:
        200:
            description: List of all amenities for the place
            schema:
                $ref: '#/definitions/get_amenities_get_Amenities'
    """
    try:
        ''' Check if the place exists '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Return amenities for the given place '''
        data = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Example #2
0
def get_users():
    """
    Get all users
    List all users in the database.
    ---
    tags:
        - User
    responses:
        200:
            description: List of all users
            schema:
                id: Users
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: users array
                        items:
                            $ref: '#/definitions/get_user_get_User'
                    paging:
                        description: pagination
                        schema:
                            $ref: '#/definitions/get_amenities_get_Paging'
    """
    data = User.select()
    return ListStyle.list(data, request), 200
Example #3
0
def users():
    if request.method == 'GET':
        try:
            # Getting all the users
            list = ListStyle.list(User.select(), request)
            return jsonify(list)
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'users not found'}), 404)

    elif request.method == 'POST':
        user_email = request.form["email"]
        user_password = request.form["password"]
        user_first_name = request.form["first_name"]
        user_last_name = request.form["last_name"]
        try:
            new_user = User(email=user_email,
                            first_name=user_first_name,
                            last_name=user_last_name,
                            password=md5.new(user_password).hexdigest())
            new_user.save()
            return jsonify(new_user.to_dict())
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'email already exist'}), 409)
Example #4
0
def get_states():
    """
    Get all states
    List all states in the database.
    ---
    tags:
        - State
    responses:
        200:
            description: List of all states
            schema:
                id: States
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: states array
                        items:
                            $ref: '#/definitions/get_state_get_State'
                    paging:
                        description: pagination
                        schema:
                            $ref: '#/definitions/get_amenities_get_Paging'
    """
    try:
        ''' Returns a list of states in list named result '''
        data = State.select()
        return ListStyle.list(data, request), 200
    except Exception as e:
        abort(500)
Example #5
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())
Example #6
0
def cities(state_id):
    if request.method == 'GET':
        try:
            query = City.select().where(City.state == state_id)

            return ListStyle.list(query, request), 200

        except City.DoesNotExist:
            return json_response(status_=404, msg="not found")

    elif request.method == 'POST':
        if "name" not in request.form:
            return json_response(status_=400,
                                 msg="missing parameters",
                                 code=40000)

        city_test = City.select().where(City.name == str(request.form["name"]),
                                        City.state == state_id)

        if city_test.wrapped_count() > 0:
            return json_response(status_=409,
                                 code=10002,
                                 msg="city already exists in this state")

        city = City(name=str(request.form["name"]), state=str(state_id))
        city.save()
        return jsonify(city.to_dict()), 201
Example #7
0
def users():
    if request.method == 'GET':
        try:
            # Getting all the users
            list = ListStyle.list(User.select(), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'users not found'
                }), 404)

    elif request.method == 'POST':
        user_email = request.form["email"]
        user_password = request.form["password"]
        user_first_name = request.form["first_name"]
        user_last_name = request.form["last_name"]
        try:
            new_user = User(email=user_email,
                            first_name=user_first_name,
                            last_name=user_last_name,
                            password=md5.new(user_password).hexdigest())
            new_user.save()
            return jsonify(new_user.to_dict())
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'email already exist'
                }), 409)
Example #8
0
def get_places_by_city(state_id, city_id):
    """
    Get a place with id as place_id and state with  id as state_id
    """
    city = City.get(City.id == city_id, City.state == state_id)
    data = Place.select().where(Place.city == city.id)
    return ListStyle.list(data, request), 200
Example #9
0
def get_places():
    """
    Get all places
    List all places in the database.
    ---
    tags:
        - Place
    responses:
        200:
            description: List of all places
            schema:
                id: Places
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: places array
                        items:
                            $ref: '#/definitions/get_place_get_Place'
                    paging:
                        description: pagination
                        schema:
                            $ref: '#/definitions/get_amenities_get_Paging'
    """
    data = Place.select()
    return ListStyle.list(data, request), 200
Example #10
0
def amenities_place(place_id):
	if request.method == "GET":
		try:
			query = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id)
			return ListStyle.list(query, request), 200

		except:
			return json_response(status_=404, msg="Not found")
Example #11
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
Example #12
0
def state_places(state_id):
	state = State.select().where(State.id == state_id)

	if state.wrapped_count() < 1:
		return json_response(status_=404, code=10002, msg="state not found")

	query = Place.select().join(City).join(State).where(State.id == state_id)

	return ListStyle.list(query, request)
Example #13
0
def get_places_by_state(state_id):
    """
    Get a place in a state with id as state_id
    """
    try:
        query = City.select().where(City.state == state_id)
        if not query.exists():
            return ListStyle.list(query, request), 200
        cities = []
        for city in query:
            cities.append(city.id)

        data = Place.select().where(Place.city << cities)
        return ListStyle.list(data, request), 200
    except Exception as e:
        res = {}
        res['code'] = 500
        res['msg'] = str(error)
        return res, 500
Example #14
0
def get_places_by_state(state_id):
    """
    Get all places by state
    List all places in the given state in the database.
    ---
    tags:
        - Place
    parameters:
        -
            name: state_id
            in: path
            type: integer
            required: True
            description: ID of the state
    responses:
        200:
            description: List of all places in state
            schema:
                $ref: '#/definitions/get_places_get_Places'
    """
    try:
        ''' Check if state exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state_id')

        ''' Create a list of city ids in the state '''
        query = City.select().where(City.state == state_id)
        if not query.exists():
            return ListStyle.list(query, request), 200
        cities = []
        for city in query:
            cities.append(city.id)

        ''' Return the places in listed cities '''
        data = Place.select().where(Place.city << cities)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        print e.message
        abort(500)
Example #15
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)
Example #16
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)
Example #17
0
def get_user_reviews(user_id):
	"""
	Get all user reviews
	List all user reviews in the database.
	---
	tags:
	    - Review
	parameters:
		-
			in: path
			name: user_id
			type: string
			required: True
			description: ID of the user
	responses:
	    200:
	        description: List of all user reviews
	        schema:
	            id: UserReviews
	            required:
	                - data
	                - paging
	            properties:
	                data:
	                    type: array
	                    description: user reviews array
	                    items:
	                        $ref: '#/definitions/get_user_review_get_UserReview'
	                paging:
	                    description: pagination
	                    schema:
	                        $ref: '#/definitions/get_amenities_get_Paging'
	"""
	try:
		''' Test if user_id exists '''
		query = User.select().where(User.id == user_id)
		if not query.exists():
			raise LookupError('user_id')

		''' Get list of reviews for the user and return response '''
		reviews = Review.select(Review, ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id)
		return ListStyle.list(reviews, request), 200
	except LookupError as e:
		abort(404)
	except Exception as e:
		print e.message
		res = {
			'code': 500,
			'msg': e.message
		}
		return res, 500
Example #18
0
def get_places_by_city(state_id, city_id):
    """
    Get all places
    List all places in the given city in the database.
    ---
    tags:
        - Place
    parameters:
        -
            name: state_id
            in: path
            type: integer
            required: True
            description: ID of the state
        -
            name: city_id
            in: path
            type: integer
            required: True
            description: ID of the city
    responses:
        200:
            description: List of all places
            schema:
                $ref: '#/definitions/get_places_get_Places'
    """
    try:
        ''' Check if the state_id exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state_id')

        ''' Check if the city_id exists '''
        query = City.select().where(City.id == city_id)
        if not query.exists():
            raise LookupError('city_id')

        ''' Check if the city_id is associated to the state_id '''
        city = City.get(City.id == city_id)
        query = State.select().where(State.id == city.state, State.id == state_id)
        if not query.exists():
            raise LookupError('city_id, state_id')

        ''' Return all places in the given city '''
        data = Place.select().where(Place.city == city.id)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as error:
        abort(500)
Example #19
0
def get_place_reviews(place_id):
    try:
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')
        reviews = Review.select(
            Review,
            ReviewPlace).join(ReviewPlace).where(ReviewPlace.place == place_id)
        return ListStyle.list(reviews, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {'code': 500, 'msg': e.message}
        return res, 500
Example #20
0
def place_reviews(place_id):
	place_test = Place.select().where(Place.id == place_id)

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

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

		return ListStyle.list(query, request), 200

	elif request.method == "POST":
		if "message" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "user_id" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "stars" not in request.form:
			# if type(request.form["message"]) != str:
			# 	return json_response(status_=400, msg="invalid data type for message")

			# if type(request.form["user_id"] != int):
			# 	return json_response(status_=400, msg="invalid data type for user id")

			review = Review(message=str(request.form["message"]), user=request.form["user_id"])
			review.save()

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

			return jsonify(review.to_dict()), 201

		else:
			# if type(request.form["message"]) != str:
			# 	return json_response(status_=400, msg="invalid data type for message")

			# if type(request.form["user_id"] != int):
			# 	return json_response(status_=400, msg="invalid data type for user id")

			# if type(request.form["stars"] != int):
			# 	return json_response(status_=400, msg="invalid data type for stars")

			review = Review(message=str(request.form["message"]), user=request.form["user_id"], stars=int(request.form["stars"]))
			review.save()

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

			return jsonify(review.to_dict()), 201
Example #21
0
def get_reviews_user(user_id):
    # Checking if an user exist
    try:
        User.get(User.id == user_id)
    except User.DoesNotExist:
        return jsonify(msg="There is no user with this id."), 404

    # Getting all the review by user id
    if request.method == "GET":
        try:
            # Checking if a review exist on a specific user
            try:
                ReviewUser.get(ReviewUser.user == user_id)
            except:
                return jsonify(
                    msg="There is no review for an user with this id."), 404
            # retriving the reviews an user received
            list = ListStyle.list(
                User.select().join(ReviewUser).where(
                    ReviewUser.user == User.id).where(
                        ReviewUser.user == user_id), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)

    elif request.method == "POST":
        user_message = request.form["message"]
        user_stars = request.form["stars"]

        try:
            new_review = Review(message=user_message,
                                stars=user_stars,
                                user=user_id)
            new_review.save()

            user_review = ReviewUser(user=user_id, review=new_review.id)
            user_review.save()

            return jsonify(new_review.to_dict())
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Example #22
0
def list_of_states():
    if request.method == 'GET':
        list = ListStyle.list(State.select(), request)
        return jsonify(list)

    if request.method == 'POST':
        # name_state = request.form['name']
        try:
            new_state = State(name=request.form['name'])
            # saving the changes
            new_state.save()
            # returning the new information in hash form
            return "New State entered! -> %s\n" % (new_state.name)
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'State already exist'}), 409)
Example #23
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)
Example #24
0
def get_user_reviews(user_id):
    """
    Get user Reviews of user with id as user_id
    """
    try:
        query = User.select().where(User.id == user_id)
        if not query.exists():
            raise LookupError('user_id')
        reviews = Review.select(
            Review,
            ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id)
        return ListStyle.list(reviews, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {'code': 500, 'msg': e.message}
        return res, 500
Example #25
0
def modify_city(state_id, city_id):
    id = city_id
    try:
        if request.method == 'GET':
            list = ListStyle.list(
                City.select().where(City.id == city_id
                                    and City.state == state_id), request)
            return jsonify(list)
    except:
        return "City with id %d does not exist" % (int(id))
    if request.method == "DELETE":
        id = city_id
        try:
            get_city = City.get(City.id == id)
            get_city.delete_instance()
            return "City with id %d was deleted\n" % (int(id))
        except:
            return "City with id %d does not exist\n" % (int(id))
Example #26
0
def modify_city(state_id, city_id):
    id = city_id
    try:
        if request.method == 'GET':
            list = ListStyle.list(City.select()
                                  .where(City.id == city_id
                                         and City.state == state_id), request)
            return jsonify(list)
    except:
        return "City with id %d does not exist" % (int(id))
    if request.method == "DELETE":
        id = city_id
        try:
            get_city = City.get(City.id == id)
            get_city.delete_instance()
            return "City with id %d was deleted\n" % (int(id))
        except:
            return "City with id %d does not exist\n" % (int(id))
Example #27
0
def places():
	if request.method == 'GET':
		list_places = Place.select()
		
		return ListStyle.list(list_places, request), 200

	elif request.method == 'POST':
		if "name" not in request.form or "owner_id" not in request.form or "city" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		test = Place.select().where(Place.name == request.form["name"])

		if test.wrapped_count() > 0:
			return json_response(status_=409, code=10002, msg="place already exists with this name")

		try:
			entry = Place(owner=request.form["owner_id"], name=request.form["name"], city=request.form["city"])

			if request.form['description']:
				entry.description = str(request.form['description'])

			if request.form['number_rooms']:
				entry.number_rooms = int(request.form['number_rooms'])

			if request.form['number_bathrooms']:
				entry.number_bathrooms = int(request.form['number_bathrooms'])

			if request.form['max_guest']:
				entry.max_guest = int(request.form['max_guest'])

			if request.form['price_by_night']:
				entry.price_by_night = int(request.form['price_by_night'])

			if request.form['latitude']:
				entry.latitude = float(request.form['latitude'])

			if request.form['longitude']:
				entry.longitude = float(request.form['longitude'])

			entry.save()
			return jsonify(entry.to_dict()), 201

		except IntegrityError:
			return json_response(status_=400, msg="you are missing a field in your post request")
Example #28
0
def get_list_places(state_id):
    try:
        # Checking if a state exist
        State.get(State.id == state_id)
    except State.DoesNotExist:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Place not found'}), 404)
    if request.method == 'GET':
        try:
            # getting a place that is in a specific state
            list = ListStyle.list(Place.select()
                                  .join(City)
                                  .where(Place.city == City.id)
                                  .join(State)
                                  .where(State.id == City.state), request)
            return jsonify(list)
        except:
            return make_response(jsonify({'code': '10001',
                                          'msg': 'Place not found'}), 404)
Example #29
0
def list_of_states():
    if request.method == 'GET':
        list = ListStyle.list(State.select(), request)
        return jsonify(list)

    if request.method == 'POST':
        # name_state = request.form['name']
        try:
            new_state = State(name=request.form['name'])
            # saving the changes
            new_state.save()
            # returning the new information in hash form
            return "New State entered! -> %s\n" % (new_state.name)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'State already exist'
                }), 409)
Example #30
0
def list_cities(state_id):
    id_state = state_id
    # returns a json with the cities associated to a state
    if request.method == 'GET':
        list = ListStyle.list(City.select()
                              .where(City.state == id_state), request)
        return jsonify(list)
    # creates a new city
    elif request.method == 'POST':
        # checks if the city already exist in the state
        for city in City.select():
            if str(city.state_id) == id_state and city.name == request.form['name']:
                return make_response(jsonify({'code': '10001',
                                              'msg': 'City already exists in this state'}), 409)

        city_name = request.form['name']
        new_city = City(name=city_name, state_id=id_state)
        new_city.save()
        return "New city saved %s\n" % (new_city.name)
Example #31
0
def states():
	if request.method == 'GET':
		query = State.select()

		return ListStyle.list(query, request), 200

	elif request.method == 'POST':
		try:
			if "name" not in request.form:
				return json_response(status_=400, msg="missing parameters", code=40000)

			insert = State(name=str(request.form["name"]))
			insert.save()
			return jsonify(insert.to_dict()), 201

		except IntegrityError:
			return json_response(status_=409,
								code=10001,
								msg="State already exists")
Example #32
0
def get_review_place(place_id):
    try:
        # Checking if place exist
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return make_response(
            jsonify({
                'code': 10000,
                'msg': 'Place not found'
            }), 404)
    if request.method == 'GET':
        try:
            # Getting the all the reviews for a place
            list = ListStyle.list(
                Review.select().join(ReviewPlace).where(
                    ReviewPlace.review == Review.id).where(
                        ReviewPlace.place == place_id), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
    elif request.method == 'POST':
        user_message = request.form["message"]
        user_stars = request.form["stars"]
        try:
            new_review = Review(message=user_message,
                                stars=user_stars,
                                user=place_id)  # using the place_id as user?
            new_review.save()

            review_place = ReviewPlace(review=new_review.id, place=place_id)
            review_place.save()
            return jsonify(new_review.to_dict())
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Example #33
0
def list_of_place():
    # returning a list of all places
    if request.method == 'GET':
        list = ListStyle.list(Place.select(), request)
        return jsonify(list)

    if request.method == 'POST':
        new_place = Place(owner=request.form['owner'],
                          city=request.form['city'],
                          name=request.form['name'],
                          description=request.form['description'],
                          number_rooms=request.form['number_rooms'],
                          number_bathrooms=request.form['number_bathrooms'],
                          max_guest=request.form['max_guest'],
                          price_by_night=request.form['price_by_night'],
                          latitude=request.form['latitude'],
                          longitude=request.form['longitude']
                          )
        new_place.save()
        return "place created"
Example #34
0
def get_amenities():
    """
    Get all amenities
    List all amenities in the database.
    ---
    tags:
        - Amenity
    responses:
        200:
            description: List of all amenities
            schema:
                id: Amenities
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: amenities array
                        items:
                            $ref: '#/definitions/get_amenity_get_Amenity'
                    paging:
                        description: pagination
                        schema:
                            id: Paging
                            required:
                                - next
                                - prev
                            properties:
                                next:
                                    type: string
                                    description: next page URL
                                    default: "/<path>?page=3&number=10"
                                prev:
                                    type: string
                                    description: previous page URL
                                    default: "/<path>?page=1&number=10"
    """
    data = Amenity.select()
    return ListStyle.list(data, request), 200
Example #35
0
def get_cities(state_id):
    """
    Get all cities
    List all cities in the database.
    ---
    tags:
        - City
    responses:
        200:
            description: List of all cities
            schema:
                id: Cities
                required:
                    - data
                    - paging
                properties:
                    data:
                        type: array
                        description: cities array
                        items:
                            $ref: '#/definitions/get_city_get_City'
                    paging:
                        description: pagination
                        schema:
                            $ref: '#/definitions/get_amenities_get_Paging'
    """
    try:
        ''' Check if state exists '''
        query = State.select().where(State.id == state_id)
        if not query.exists():
            raise LookupError('state')

        ''' Return list of cities in given state '''
        data = City.select().where(City.state == state_id)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Example #36
0
def users():
	if request.method == "POST":
		try:
			if "email" not in request.form or "password" not in request.form or "first_name" not in request.form or "last_name" not in request.form:
				return json_response(status_=400, code=40000, msg="missing parameters")
				
			new_user = User(email=request.form["email"],
							password=request.form["password"],
							first_name=request.form["first_name"],
							last_name=request.form["last_name"])
			new_user.save()
			return jsonify(new_user.to_dict()), 201

		except IntegrityError:
			return json_response(status_=409,
								msg="Email already exists",
								code=10000)

	elif request.method == "GET":
		query = User.select()

		return ListStyle.list(query, request), 200
Example #37
0
def cities(state_id):
	if request.method == 'GET':
		try:
			query = City.select().where(City.state == state_id)

			return ListStyle.list(query, request), 200

		except City.DoesNotExist:
			return json_response(status_=404, msg="not found")

	elif request.method == 'POST':
		if "name" not in request.form:
			return json_response(status_=400, msg="missing parameters", code=40000)

		city_test = City.select().where(City.name == str(request.form["name"]), City.state == state_id)

		if city_test.wrapped_count() > 0:
			return json_response(status_=409, code=10002, msg="city already exists in this state") 

		city = City(name=str(request.form["name"]), state=str(state_id))
		city.save()
		return jsonify(city.to_dict()), 201
Example #38
0
def delete_reviews_place(place_id, review_id):
    try:
        # Checking if place exist
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return make_response(jsonify({'code': 10000, 'msg': 'Not found'}), 404)
    if request.method == 'GET':
        try:
            # Checking if a review exist
            Review.get(Review.id == review_id)
            # Getting the review for a place
            list = ListStyle.list(
                Review.select().join(ReviewPlace).where(
                    ReviewPlace.review == Review.id).where(
                        ReviewPlace.place == place_id
                        and ReviewPlace.review == review_id), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
    elif request.method == 'DELETE':
        try:
            place_review = (ReviewPlace.get(ReviewPlace.place == place_id
                                            & ReviewPlace.review == review_id))
            place_review.delete_instance()

            get_review = Review.get(Review.id == review_id)
            get_review.delete_instance()
            return "Review was deleted"
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Example #39
0
def amenities():
	if request.method == 'GET':
		amenities = Amenity.select()
		return ListStyle.list(amenities, request), 200

	elif request.method == 'POST':
		try:
			if "name" not in request.form:
				return json_response(status_=400, msg="missing parameters", code=40000)
				
			test = Amenity.select().where(Amenity.name == request.form["name"])

			if test.wrapped_count() > 0:
				return json_response(status_=409, code=10002, msg="place already exists with this name")

			amenity = Amenity(name=request.form["name"])
			amenity.save()
			return jsonify(amenity.to_dict()), 201

		except IntegrityError:
			return json_response(status_=409,
								msg="Name already exists",
								code=10003)
Example #40
0
def list_cities(state_id):
    id_state = state_id
    # returns a json with the cities associated to a state
    if request.method == 'GET':
        list = ListStyle.list(City.select().where(City.state == id_state),
                              request)
        return jsonify(list)
    # creates a new city
    elif request.method == 'POST':
        # checks if the city already exist in the state
        for city in City.select():
            if str(city.state_id
                   ) == id_state and city.name == request.form['name']:
                return make_response(
                    jsonify({
                        'code': '10001',
                        'msg': 'City already exists in this state'
                    }), 409)

        city_name = request.form['name']
        new_city = City(name=city_name, state_id=id_state)
        new_city.save()
        return "New city saved %s\n" % (new_city.name)
Example #41
0
def users():
    if request.method == "POST":
        try:
            if "email" not in request.form or "password" not in request.form or "first_name" not in request.form or "last_name" not in request.form:
                return json_response(status_=400,
                                     code=40000,
                                     msg="missing parameters")

            new_user = User(email=request.form["email"],
                            password=request.form["password"],
                            first_name=request.form["first_name"],
                            last_name=request.form["last_name"])
            new_user.save()
            return jsonify(new_user.to_dict()), 201

        except IntegrityError:
            return json_response(status_=409,
                                 msg="Email already exists",
                                 code=10000)

    elif request.method == "GET":
        query = User.select()

        return ListStyle.list(query, request), 200
Example #42
0
def places_within_city(state_id, city_id):
    response = jsonify({'code': 404, 'msg': 'not found'})
    response.status_code = 404

    # Getting the information for the place
    if request.method == 'GET':
        try:
            list = ListStyle.list(Place.select()
                                  .join(City)
                                  .where(City.id == city_id)
                                  .where(Place.city == city_id,
                                         City.state == state_id), request)
            return jsonify(list)
        except:
            return response
    # Creating a new place
    elif request.method == 'POST':
        try:
            # Getting the city to check if it exist
            City.get(City.id == city_id, City.state == state_id)
            # adding city by Using Post
            add_place = Place.create(owner=request.form['owner'],
                                     city=city_id,
                                     name=request.form['name'],
                                     description=request.form['description'],
                                     number_rooms=request.form['number_rooms'],
                                     number_bathrooms=request.form['number_bathrooms'],
                                     max_guest=request.form['max_guest'],
                                     price_by_night=request.form['price_by_night'],
                                     latitude=request.form['latitude'],
                                     longitude=request.form['longitude'])
            add_place.save()
            return jsonify(add_place.to_dict())
            print("You've just added a place!")
        except:
            return response
Example #43
0
def user_reviews(user_id):
	user_test = User.select().where(User.id == user_id)

	if user_test.wrapped_count() < 1:
		return json_response(status_=404, msg="user does not exist with that id")

	if request.method == "GET":
		query = ReviewUser.select().where(ReviewUser.user == user_id) 

		return ListStyle.list(query, request), 200


	elif request.method == "POST":
		if "message" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "user_id" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "stars" not in request.form:
			review = Review(message=str(request.form["message"]), user=request.form["user_id"])
			review.save()

			u_review = ReviewUser(user=user_id, review=review.id)
			u_review.save()

			return jsonify(review.to_dict()), 201

		else:
			review = Review(message=str(request.form["message"]), user=request.form["user_id"], stars=int(request.form["stars"]))
			review.save()

			u_review = ReviewUser(user=user_id, review=review.id)
			u_review.save()

			return jsonify(review.to_dict()), 201
Example #44
0
def state_city_place(state_id, city_id):
	if request.method == "GET":
		try:
			state_test = State.select().where(State.id == state_id)

			if state_test.wrapped_count() < 1:
				return json_response(status_=404, code=10002, msg="state not found") 

			city_test = City.select().where(City.id == city_id)

			if city_test.wrapped_count() < 1:
				return json_response(status_=404, code=10002, msg="state not found") 

			query = Place.select().where(Place.city == city_id)

			return ListStyle.list(query, request), 200

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

	elif request.method == "POST":
		if "name" not in request.form or "owner_id" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		try:
			city = City.get(City.id == city_id, City.state_id == state_id)

		except City.DoesNotExist:
			return json_response(status_=404, msg="City does not exist")

		try:
			place = Place(owner=request.form['owner_id'],
						city=city_id,
						name=request.form['name'])

			if request.form['description']:
				place.description = str(request.form['description'])

			if request.form['number_rooms']:
				place.number_rooms = int(request.form['number_rooms'])

			if request.form['number_bathrooms']:
				place.number_bathrooms = int(request.form['number_bathrooms'])

			if request.form['max_guest']:
				place.max_guest = int(request.form['max_guest'])

			if request.form['price_by_night']:
				place.price_by_night = int(request.form['price_by_night'])

			if request.form['latitude']:
				place.latitude = float(request.form['latitude'])

			if request.form['longitude']:
				place.longitude = float(request.form['longitude'])

			place.save()

		except IntegrityError:
			return json_response(status_=409, msg="Name already exists")

        return jsonify(place.to_dict()), 201
Example #45
0
def list_amenities():
    try:
        list = ListStyle.list(Amenity.select(), request)
        return jsonify(list)
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
Example #46
0
def get_amenities():
    """
    Get all amenities
    """
    data = Amenity.select()
    return ListStyle.list(data, request), 200
Example #47
0
def get_cities(state_id):
    """
    Get all cities
    """
    data = City.select().where(City.state == state_id)
    return ListStyle.list(data, request), 200
Example #48
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
Example #49
0
def get_states():
    """
    Get all states
    """
    data = State.select()
    return ListStyle.list(data, request), 200
Example #50
0
def list_amenities():
    try:
        list = ListStyle.list(Amenity.select(), request)
        return jsonify(list)
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404