Esempio n. 1
0
def index():
    form = PhotoForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = secure_filename(f.filename)
        # f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # os.rename(os.path.join(app.config['UPLOAD_FOLDER'], filename), os.path.join(app.config['DISPLAY_FOLDER'], filename))
        # path = os.path.join(app.config['FINAL_FOLDER'], filename)

        s3 = boto3.resource('s3')

        if filename.rsplit('.', 1)[1].lower() in set(['jpg', 'jpeg']):
            # s3.Bucket('caption-maker-bucket').put_object(Key='image_{}.jpg'.format(db.session.query(Image).count()+1), Body=f)
            # stored_as = 'image_{}.jpg'.format(db.session.query(Image).count()+1)
            # image = Image(filepath = 'https://s3.amazonaws.com/caption-maker-bucket/' + stored_as, caption = caption)
            stored_as = 'uploaded_image.jpg'
            s3.Bucket('caption-maker-bucket').put_object(Key=stored_as, Body=f)

        elif filename.rsplit('.', 1)[1].lower() in set(['png']):
            stored_as = 'uploaded_image.png'
            s3.Bucket('caption-maker-bucket').put_object(
                Key='uploaded_image.png', Body=f)

        # db.session.add(image)
        # db.session.commit()

        # flash(caption)
        return redirect(url_for('caption', filename=stored_as))
    return render_template('index.html', title='The Caption App', form=form)
Esempio n. 2
0
def add_photo(book, num):
    """
    Manually editing the db to add photos is the literal worst idea I've ever had
    :param book: title of book
    :param num: chapter number
    :return: page with a form, or if chapter is invalid, redirect to index
    """
    try:
        bookenum = Book[book.lower()]
        c = Chapter.query.filter_by(num=num, booknum=bookenum.value).first()
        if c:
            f = PhotoForm()
            if f.validate_on_submit():
                app.logger.debug(SECRET_TO_ADD_PHOTOS + " vs " + f.password.data)
                if f.password.data == SECRET_TO_ADD_PHOTOS:
                    if c.photo_url is None:
                        c.photo_url = f.urls_to_add.data
                    else:
                        c.photo_url += "," + f.urls_to_add.data
                    db.session.commit()
                    return redirect(url_for("chapter", book=book, num=num))
                else:
                    return "get out of my house"
            return render_template("add_photo.html", c=c, form=f)
    except KeyError:
        pass
    abort(404)
Esempio n. 3
0
def upload():
    form = PhotoForm()
    imgs = os.listdir(UPLOADED_PHOTOS_DEST)
    if form.validate_on_submit():
        filename = secure_filename(form.photo.data.filename)
        form.photo.data.save(os.path.join(UPLOADED_PHOTOS_DEST, filename))
        imgs = os.listdir(UPLOADED_PHOTOS_DEST)
        return render_template('uploads.html', form = form, imgs = imgs)
    return render_template('uploads.html', form = form, imgs = imgs)
Esempio n. 4
0
def index():
    form = PhotoForm()
    session['letters'] = None
    if form.validate_on_submit():
        f = form.photo.data
        filename = secure_filename(f.filename)
        filename = os.path.join(app.instance_path, 'photos', filename)
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        f.save(filename)
        session['current_img'] = filename
        return redirect(url_for('result'))
    return render_template('index.html', form=form)
Esempio n. 5
0
def photoaddress():
    #adding a form for imputting a photo
    form = PhotoForm(csrf_enabled=False)
    #When submit has clicked
    if form.validate_on_submit():
        #defininging photo as imputed photo
        photo = form.photo.data
        #create file path
        filename = photo.filename.replace(' ', '')

        basepath = os.path.abspath('app/')

        photo.save(f'/{basepath}/uploads/{filename}')
        upload_filepath = f'/{basepath}/uploads/{filename}'
        # run lat_long / heading function, streetview function, and zillow function

        address = latlong_to_address(f'{basepath}/uploads/{filename}')

        price = zillow_pull(address)
        address = address['name']

        # Set image_url to Google Street View of address

        ## Get coordinates and pull street view with coords and heading
        coords = get_coordinates(f'{basepath}/uploads/{filename}')

        heading = coords[1]
        coords = coords[0]

        image_url = f'https://maps.googleapis.com/maps/api/streetview?size=600x600&location={coords[0]}, {coords[1]}&heading={heading}&key={google_key}'

        # Image path handling
        image = requests.get(image_url)

        filelist = re.findall(r'\w+', address)
        filename2 = ''.join(filelist)
        final_path = f'{basepath}/uploads/{filename2}.jpg'
        open(f'{final_path}', 'wb').write(image.content)

        # redirect to photo_form page
        return redirect(
            url_for('surveyform',
                    price=price,
                    address=address,
                    goog_photo=f'{filename2}.jpg',
                    filename=filename,
                    coords=coords,
                    basepath=basepath))

        # return render_template('photo_form.html', form=SurveyForm(), filename = filename, address = address, price = price, goog_photo = f'{filename2}.jpg')

    return render_template('index.html', form=form)
Esempio n. 6
0
def photoaddress():
    form = PhotoForm(csrf_enabled=False)

    if form.validate_on_submit():
        photo = form.photo.data

        filename = photo.filename.replace(' ', '')

        basepath = os.path.abspath('app/')

        photo.save(f'/{basepath}/uploads/{filename}')

        # run lat_long / heading function, streetview function, and zillow function

        address = latlong_to_address(f'{basepath}/uploads/{filename}')

        # assign all to database
        price = zillow_pull(address)
        address = address['name']

        # Set image_url to Google Street View of address
        # I don't know how this will need to be saved / returned for use in Flask

        ## CHANGE THIS TO GET COORDS AND HEADING FOR CORRECT IMAGE
        coords = get_coordinates(f'{basepath}/uploads/{filename}')

        heading = coords[1]
        coords = coords[0]

        image_url = f'https://maps.googleapis.com/maps/api/streetview?size=600x600&location={coords[0]}, {coords[1]}&heading={heading}&key={google_key}'
        ## CHANGE CHANGE CHANGE

        # Put image handling code for Flask here
        image = requests.get(image_url)

        filelist = re.findall(r'\w+', address)
        filename2 = ''.join(filelist)
        final_path = f'{basepath}/uploads/{filename2}.jpg'
        open(f'{final_path}', 'wb').write(image.content)

        # return render_template to photo_form page
        return redirect(
            url_for('surveyform',
                    price=price,
                    address=address,
                    goog_photo=f'{filename2}.jpg',
                    filename=filename))
        # return render_template('photo_form.html', form=SurveyForm(), filename = filename, address = address, price = price, goog_photo = f'{filename2}.jpg')

    return render_template('index.html', form=form)
Esempio n. 7
0
def profile(username):
    user = User.query.filter_by(username=username).first_or_404()
    profile_id = str(user.id)
    title = f"{user.firstname} {user.surname}".title()
    posts = [
        {
            "user": user,
            "body": "Test post #1"
        },
        {
            "user": user,
            "body": "Test post #2"
        },
    ]
    is_profile_of_user = current_user == user
    photo_form = PhotoForm()
    delete_photo_form = DeletePhotoForm()
    if delete_photo_form.deletebtn.data and delete_photo_form.validate_on_submit(
    ):
        user_id = str(current_user.id)
        existing_photo = Photo.query.filter_by(user_id=int(user_id)).first()
        if existing_photo:
            try:
                db.session.delete(existing_photo)
                db.session.commit()
            except Exception:
                photo_logger.exception(
                    f"Delete photo error for user: {user_id}")
                flash("An unexpected error occured. Please try again, "
                      "or contact support.")
            profile_path = app.config["UPLOAD_FOLDER"].joinpath(
                user_id, "profile")
            delete_all_profile_images_else_log_path(profile_path)
    if not delete_photo_form.deletebtn.data and photo_form.validate_on_submit(
    ):
        user_id = str(current_user.id)
        preserve_metadata = current_user.settings.preserve_photo_data
        save_and_resize(photo_form, user_id, preserve_metadata)
    return render_template("profile.html",
                           user=user,
                           title=title,
                           posts=posts,
                           is_profile_of_user=is_profile_of_user,
                           photo_form=photo_form,
                           delete_photo_form=delete_photo_form,
                           profile_id=profile_id)
Esempio n. 8
0
def admin_photos():
    form = PhotoForm()
    photos = db.session.query(Photo).all()

    if form.validate_on_submit():
        photo = Photo()
        photo.name = form.name.data
        photo.caption = form.caption.data
        photo.file = upload_file('file')
        photo.user_id = current_user.id

        db.session.add(photo)
        db.session.commit()
        message = Markup(
            '<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">&times;</button>Photo added successfully</div>'
        )
        flash(message)
        return redirect(url_for('admin_photos'))
    return render_template('admin/photos.html', form=form, photos=photos)
Esempio n. 9
0
def photos():
    photo_form = PhotoForm()
    if photo_form.validate_on_submit():
        if not (request.files['files'].filename!='' or photo_form.post.data):
            flash('At least one field must have a value.')
            return redirect(url_for('photos'))
        else:
            post = Post(body=photo_form.post.data,author=current_user)
            for file in photo_form.files.data:
                try:
                    filename = images.save(file)
                    photo = Photo(filename=filename, title=photo_form.post.data, post=post, is_public=1)
                    db.session.add(photo)
                except UploadNotAllowed:
                    flash('File Format Not Allowed.')
                    return redirect(url_for('photos'))
            db.session.commit()
            flash('Photo(s) Uploaded.')
            return redirect(url_for('photos'))

    photos = Photo.query.filter(Photo.is_public==1).order_by(Photo.timestamp.desc()).all()
    return render_template('photos.html', title='Photos', photo_form=photo_form, photos=photos)
Esempio n. 10
0
def home():
    postform = PostForm()
    photoform = PhotoForm()
    posts = []
    friends = []
    groups = []
    comments = []
    photo_comments = []

    friends_result = db.session.execute(
        """SELECT user.* ,login.username FROM login,user WHERE login.user_id=user.user_id
        AND login.user_id IN
        (SELECT user.user_id FROM user JOIN friends ON user.user_id=friends.friend_id JOIN login ON friends.user_id=login.user_id WHERE login.username=BINARY(:username));""",
        {"username": current_user.username})
    for row in friends_result:
        row = dict(row)
        friends.append(row)

    group_result = db.session.execute("""SELECT * FROM `group`;""")
    for row in group_result:
        row = dict(row)
        groups.append(row)

    if request.method == 'POST' and postform.validate_on_submit():
        description = postform.description.data
        db.session.execute(
            """INSERT INTO post(user_id,description) VALUES(:user_id,:description)""",
            {
                "user_id": current_user.user_id,
                "description": description
            })
        db.session.commit()
        flash("Post added Successfully.", "success")
        return redirect(url_for('home'))

    elif request.method == "POST" and photoform.validate_on_submit():
        caption = photoform.caption.data
        photo = photoform.photo.data
        if (photo):
            filename = secure_filename(photo.filename)
            photo.save(
                os.path.join(app.config['UPLOAD_FOLDER'] + '/posts', filename))
            db.session.execute(
                """INSERT INTO photos(user_id,caption,filename) VALUES(:user_id,:caption,:filename)""",
                {
                    "user_id": current_user.user_id,
                    "caption": caption,
                    "filename": filename
                })
            db.session.commit()
            flash("Post added Successfully.", "success")
            return redirect(url_for('home'))
    else:
        post_result = db.session.execute(
            """SELECT post.* FROM post ORDER BY post.post_id DESC LIMIT 5 """)
        posts = [row for row in post_result]
        comment_result = db.session.execute(
            """SELECT post.post_id,post.description, comments.comment,login.username FROM post JOIN comments ON post.post_id=comments.post_id JOIN login ON comments.user_id=login.user_id"""
        )
        for row in comment_result:
            row = dict(row)
            comments.append(row)
        photo_result = db.session.execute(
            """SELECT * FROM photos ORDER BY photo_id DESC""")
        photos = [row for row in photo_result]

        photo_comment_result = db.session.execute(
            """SELECT photos.photo_id, photos.caption,photo_comments.comment, login.username FROM photos JOIN photo_comments ON photos.photo_id=photo_comments.photo_id JOIN login ON photo_comments.user_id = login.user_id """
        )
        for row in photo_comment_result:
            row = dict(row)
            photo_comments.append(row)
        db.session.close()
        return render_template('home.html',
                               postform=postform,
                               photoform=photoform,
                               posts=posts,
                               photos=photos,
                               friends=friends,
                               groups=groups,
                               comments=comments,
                               photo_comments=photo_comments)
Esempio n. 11
0
def upload():
    form = PhotoForm()
    if form.validate_on_submit():
        print(request.files)
        print('hello')
    return render_template('upload.html', form=form)