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)
def upload_images(request, username, trip_name_slug, post_name_slug): # Construct the context Dictionary context_dict = {} try: inpost = BlogPost.objects.get(slug=post_name_slug) context_dict['post'] = inpost trip = Trip.objects.get(slug=trip_name_slug) context_dict['trip'] = trip except BlogPost.DoesNotExist: context_dict['post'] = None except Trip.DoesNotExist: context_dict['trip'] = None if request.method == 'POST': # If POST use form to create PostImage object form = PhotoForm(request.POST, request.FILES) if form.is_valid(): photo = form.save(commit=False) photo.post = inpost photo.save() # Create a JSON from the new PostImage object, and pass that in as our response, since the JS uses JSON data = { 'is_valid': True, 'name': photo.name, 'url': photo.image.url } else: data = {'is_valid': False} return JsonResponse(data) else: # If GET add current post photos to the context dict photos_list = PostImage.objects.filter(post=inpost) context_dict["photos"] = photos_list return render(request, 'app/upload_images.html', context_dict)
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)
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)
def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = { 'is_valid': True, 'name': photo.file.name, 'url': photo.file.url } else: data = {'is_valid': False} return JsonResponse(data)
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)
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)
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)
def show(self, id): from app.forms import PhotoForm self.is_print = False self.photo_form = PhotoForm() return self.template()
def add_pho(): form = PhotoForm() errors = None if request.method == 'POST': entrypho(form) return redirect(url_for('photo_list')) return render_template("add_photo.html", form=form, errors=errors)
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)
def edit_pho(entry_id): mentry = Photo.query.filter_by(id=entry_id).first_or_404() form = PhotoForm(obj=mentry) errors = None if request.method == 'POST': entrypho(form, photo_id=entry_id, photo=mentry) return redirect(url_for('photo_list')) return render_template("add_photo.html", form=form, errors=errors)
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">×</button>Photo added successfully</div>' ) flash(message) return redirect(url_for('admin_photos')) return render_template('admin/photos.html', form=form, photos=photos)
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)
def upload_photo(self, id): from werkzeug.datastructures import CombinedMultiDict from app.forms.files import PhotoForm from app.models import RecipeImageFile form = PhotoForm(CombinedMultiDict((request.files, request.form))) if form.file.data: file = RecipeImageFile(recipe_id=id) file.data = form.file.data file.save() return redirect(url_for("RecipeView:show", id=id))
def recipe(id): photo=PhotoForm() print(request.method) if request.method == 'POST' and photo.validate_on_submit: file = request.files['photo'] filename = secure_filename(file.filename) cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('Select ImgID from image order by length(ImgID) DESC,ImgID Desc Limit 1') last_img = cursor.fetchone() cursor.execute('select mealID from meals as m join recipes as r on m.RecID = r.RecID where r.RecID = %s',([id])) mealID = cursor.fetchone() print(mealID) if last_img == None: imgID = 'IMG-1' else: last = int(last_img['ImgID'].split('-')[1]) imgID = 'IMG-' + str(last+1) cursor.execute('Insert into image values(%s,%s)',(imgID,filename)) cursor.execute('Insert into meal_image values(%s,%s)',(mealID['mealID'],imgID)) mysql.connection.commit() cursor.close() file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('Select * from recipes where RecID=%s',([id])) recipe = cursor.fetchone() cursor.execute('Select * from recipe_description where DescID =%s',([recipe['DescID']])) desc = cursor.fetchone()['Desc'] cursor.execute('select mealID from meals as m join recipes as r on m.RecID = r.RecID where r.RecID = %s',([id])) mealID = cursor.fetchone()['mealID'] cursor.execute('select image from image as i join meal_image as mi on i.ImgID = mi.ImgID where mi.mealID = %s order by length(mi.ImgID) DESC,mi.ImgID Desc Limit 1 ',([mealID])) img = cursor.fetchone() if img == None: filename = 'placeholder.png' else: filename = img['image'] return render_template('recipe.html',recipe=recipe,desc=desc, form=photo, filename=filename)
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)
def upload(): form = PhotoForm() if form.validate_on_submit(): print(request.files) print('hello') return render_template('upload.html', form=form)