def create_booking_for_listing(listing_id):
    ''' Creates a booking for a user, given the listing '''
    try:
        ## Extract POST body
        post_json = request.json

        ## Parse date
        parsed_date = dateutil.parser.parse(post_json['start_date'])
        year = str(parsed_date.year)
        month = parsed_date.month
        month = '0' + str(month) if month < 10 else str(month)
        day = parsed_date.day
        day = '0' + str(day) if day < 10 else str(day)
        start_date = year + month + day

        ## Convert num nights
        num_nights = int(post_json['num_nights'])

        ## Get user
        user_id = get_user(request)

        booking = Booking(listing_id=listing_id,
                          user_id=user_id,
                          start_date=start_date,
                          num_nights=num_nights)
        db.session.add(booking)
        db.session.commit()
    except Exception as e:
        print(e)
        return '', 401  # something went wrong

    return '', 200
Exemple #2
0
def generate_img_uri(request):
    ''' Upload an image to AWS S3 then generate a URI for it to store in the picture_url field '''

    # default image URI
    default_img = 'http://thechurchontheway.org/wp-content/uploads/2016/05/placeholder1.png'

    img_uri = default_img

    if 'picture_obj' in request.files:
        try:
            # Extract image fil object from request
            image = request.files['picture_obj']
            # Generate a unique file name for image
            # based on the user ID, num. listings and current time
            user_id = get_user(request)
            num_listings = db.session.query(Listing).filter_by(
                host_id=user_id).count()
            image_name = f"user-{user_id}-listing-{num_listings}-{str(int(time.time()))}"
            # Upload image to S3
            s3.upload_fileobj(image,
                              bucket_name,
                              image_name,
                              ExtraArgs={
                                  'ACL': 'public-read',
                                  'ContentType': image.mimetype
                              })
            # Create URI
            img_uri = f"https://s3-ap-southeast-2.amazonaws.com/{bucket_name}/" + image_name
            print("Image saved:", img_uri)
        except Exception as e:
            print("image not saved")
            print(e)

    return img_uri
def get_user_bookings():
    ''' Retrieve all bookings made by a user '''
    ## Get user
    user_id = get_user(request)
    bookings = Booking.get_bookings_by_user(user_id)
    bookings = sanitize_bookings(bookings)
    ## Add info about the booking's listing
    for booking in bookings:
        listing = db.session.query(Listing).filter_by(
            id=booking['listing_id']).first()
        booking['listing_room_type'] = listing.room_type
        booking['listing_property_type'] = listing.property_type
        booking['price'] = listing.price
        booking['neighbourhood'] = listing.neighbourhood
        booking['picture_url'] = listing.picture_url

    return jsonify(bookings=bookings), 200
Exemple #4
0
def new_listing():
    ''' Create a new listing in the database (with main fields only) '''
    try:
        # Extract the form data
        form_data = request.form
        # Derive the long/lat from address
        longitude, latitude = get_coordinates(form_data['address'])
        # Ensure amenities is in same format as dataset i.e. {"Wifi", "TV", ... "Pool"}
        amenities_cleansed = preprocess_amenities(form_data['amenities'])
        # Save the image to S3 and generate an image URI to store in RDS
        img_uri = generate_img_uri(request)
        # Add new listing to db
        new_listing = Listing(name=form_data['name'],
                              description=form_data['description'],
                              neighbourhood=form_data['neighbourhood'],
                              property_type=form_data['property_type'],
                              room_type=form_data['room_type'],
                              accommodates=int(form_data['accommodates']),
                              price=float(form_data['price']),
                              transit=form_data['transit'],
                              address=form_data['address'],
                              bedrooms=int(form_data['bedrooms']),
                              beds=int(form_data['beds']),
                              bathrooms=int(form_data['bathrooms']),
                              amenities=amenities_cleansed,
                              minimum_nights=int(form_data['minimum_nights']),
                              maximum_nights=int(form_data['maximum_nights']),
                              longitude=longitude,
                              latitude=latitude,
                              house_rules=form_data['house_rules'],
                              picture_url=img_uri,
                              host_id=get_user(request))
        # Commit changes
        db.session.add(new_listing)
        db.session.commit()
        print("Listing ID for new listing:", new_listing.id)
        return '', 200

    except Exception as e:
        print(e)
        return '', 404
Exemple #5
0
def get_advertised_listings():
    ''' Retrieve a user's advertised listings '''
    user = get_user(request)
    listings = db.session.query(Listing).filter_by(host_id=user).all()
    listings = sanitize_listings(listings)
    return jsonify(listings=listings), 200