def update_annotation(token, id): files = request.files.getlist('files') request_data = json.loads(request.form['request']) image_schema = AnnouncementImageSchema() getted_user = User.query.filter(User.token == token).one() request_data['user'] = getted_user.id request_data['id'] = id announ_schema = AnnouncementSchema() announcement = announ_schema.load(data=request_data) db.session.add(announcement) db.session.flush() id = announcement.id db.session.commit() for file in files: if file and allowed_file(file.filename): filename = secure_filename(file.filename) extension = filename.split()[-1] new_filename = "upload-{}.{}".format( uuid4(), extension ) file.save(os.path.join(current_app.config['UPLOAD_FOLDER_ANNOUN'], new_filename)) img_data = { "image_path": f'/images/announcement/{new_filename}', "announcement": id } db_image = image_schema.load(img_data) db.session.add(db_image) db.session.commit() return { "result": True }, 200
def process_upload(): """Upload file to S3 and add it to database.""" # Processeses only 1 file (serially) (how do we do bulk?) user_id = session["logged_in_user"] if not user_id: flash("User Id not found") return redirect("/login") if 'file' not in request.files: flash("No file found") return redirect('/upload') file = request.files["file"] if file.filename == "": flash("No selected file") return redirect("/upload") if file and allowed_file(file.filename): filename = secure_filename(file.filename) # Save image file to s3 save_image_to_s3(filename, request.files['file']) # Save image path to db save_image_to_db(filename, user_id) flash("Image added") return redirect("/my-images")
def profile(): """Show the user information and let the user change it """ # get the user from the database. user = User.query.get(session["user_id"]) if request.method == "GET": return render_template("profile.html", user=user) # if request.method == "POST" modify current users data and commit them to the database. # check if the user provided a new avatar if request.files['avatar']: photo = request.files['avatar'] # if photo is valid then save it and add the name to the database. if photo and allowed_file(photo.filename): file_name = "%d.%s" % (uuid.uuid4(), photo.filename.rsplit( '.', 1)[1].lower()) photo.save( os.path.join(app.config['UPLOAD_FOLDER_AVATAR'], file_name)) os.remove("%s/%s" % (app.config['UPLOAD_FOLDER_AVATAR'], user.avatar)) user.avatar = file_name session["user_avatar"] = user.avatar user.firstname = request.form.get("firstname") user.lastname = request.form.get("lastname") user.email = request.form.get("email") db.session.commit() flash('You have successfully updated your information') return redirect(url_for('profile'))
def file_upload(): path = check_string(request, params.PATH) if not check_path(path): path = None if path == None: return send_error(error_codes.INVALID_PATH, "You need to specify path parameter") if not os.path.isdir(path): return send_no_dir_error(path) file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.join(path, filename) file.save(file_path) return jsonify({ "code" : error_codes.SUCCESFULL_QUERY, "path" : file_path, "message" : "File uploaded" }) return jsonify({ "code" : error_codes.UNALLOWED_EXTENSION, "message" : "Unallowed extension" })
def process_image() -> str: """Transforms an image to text and returns the the text. After processing the image is deleted. Returns: str: The textual representation of an image. """ # Check if file is sent if "file" not in request.files: return "No file found!" file = request.files["file"] # Check for empty filename if file.filename == "": return "Empty filename!" # Check if file type is valid if not allowed_file(filename=file.filename, allowed_extensions=ALLOWED_EXTENSIONS): return "Invalid file type!" if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) # Process image image_text = image_processing.process_image("{}/{}".format( app.config["UPLOAD_FOLDER"], filename)) os.remove(os.path.join(app.config["UPLOAD_FOLDER"], filename)) return image_text
def upload_file(): # User reached route via POST (as by submitting a form via POST) if request.method == 'POST': # retrieve image file object form request form file = request.files['image'] # query file for correct formating if file and allowed_file(file.filename): # retrieve the filename of the file securely #avoiding cross-scripting filename = secure_filename(file.filename) # save file to local upload folder file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # connect to the database # insert user's post details from the request form to the database with engine.connect() as connection: s = posts.insert().values( user=session["username"], title=request.form.get("title"), description=request.form.get("description"), location=request.form.get("location"), image=filename, text=request.form.get("body"), date=datetime.datetime.now()) connection.execute(s) # render management page of user's posts return redirect("/manage") else: # render the add page for creating user's posts return render_template('add.html')
def article(): if request.method == "POST": userid = session["user_id"] title = request.form.get("title") description = request.form.get("description") content = request.form.get("content") like = 0 dislike =0 if not title or not description or not content: return render_template ("add_article.html", msg="Title, Description and Content fields must be filled") file = request.files['image'] if not allowed_file(file.filename): return render_template("add_article.html", msg="Wrong file type selected. You can only use png, jpg, jpeg and gif") filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) image = UPLOAD_FOLDER + filename # return redirect(url_for('uploaded_file', filename=filename)) db.execute("INSERT INTO articles ('userid', 'title', 'description', 'content','like', 'dislike', 'image') VALUES (:userid, :title, :description, :content, :like, :dislike, :image)", userid=userid, title=title, description=description, content=content, like=like, dislike=dislike, image=image) return redirect("/viewall") else: return render_template("add_article.html")
def sell(): """add a listing to sell""" if request.method == "POST": # store the photo that user provided and get the current user from the database. photo = request.files['photo'] file_name = "" user = User.query.get(session["user_id"]) if photo and allowed_file(photo.filename): # Generate a uuid4 as a name for the users avatar. file_name = "%d.%s" % (uuid.uuid4(), photo.filename.rsplit( '.', 1)[1].lower()) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name)) # Store new item in database. new_item = Item(user_id=session["user_id"], \ price=request.form.get("price"), \ title=request.form.get("title"), description=request.form.get("description"), \ photo=file_name, category=request.form.get("category"), country=user.country, \ state=user.state, city=user.city) # add new_item to the database session and commit. db.session.add(new_item) db.session.commit() # redirect user to index page. return redirect(url_for("index")) # if request.method == "Get" return render_template("sell.html", categories=app.config['CATEGORIES'])
def upload_packages(): file = request.files['file'] if file and helpers.allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(config.STORAGE_DIR, filename)) repo_browser.update_yum_repo() return "Ok" abort(404)
def add_art(): title = request.form.get('title') images_from_files = request.files.getlist('image-from-file') images_from_urls = request.form.getlist('image-from-url') images = [] for local_image in request.form.getlist('local-image'): if local_image == 'true': file = images_from_files[0] images_from_files.pop(0) if file.filename == '': flash('No file selected', 'error') return redirect('/') if file and helpers.allowed_file(file.filename, ALLOWED_EXTENSIONS): filename = secure_filename(file.filename) filename = helpers.prepend_date_time_to_string(filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) image = filename images.append(image) else: flash('File extension not allowed', 'error') return redirect('/') elif local_image == 'false': image = images_from_urls[0] images_from_urls.pop(0) if image != '': image = helpers.download(image, UPLOAD_FOLDER) images.append(image) else: flash('Image url was empty', 'error') return redirect('/') images_string = ','.join(images) g.db = connect_db() if request.form.get('existing-artist') == 'true': artist_id = request.form.get('artist-id') else: artist_name = request.form.get('artist-name') artist_website = request.form.get('artist-website') cursor = g.db.execute('INSERT into artist(name, website) VALUES(?,?)', (artist_name, artist_website)) artist_id = cursor.lastrowid source = request.form.get('source') cursor = g.db.execute('INSERT into art(title, image_url, artist_id, source) VALUES(?,?,?,?)', (title, images_string, artist_id, source)) art_id = cursor.lastrowid tags = request.form.getlist('tags') if tags != []: for tag in tags: g.db.execute('INSERT into art_tag(art_id, tag_id) VALUES(?, ?)', (art_id, tag)) g.db.commit() g.db.close() return redirect('/art/' + str(art_id))
def test_valid_file_extention(): from helpers import allowed_file from constants import ALLOWED_EXTENSIONS example_files = {"test.jpg", "test.png", "test.jpeg"} for file in example_files: assert allowed_file(filename=file, allowed_extensions=ALLOWED_EXTENSIONS)
def test_invalid_file_extension(): from helpers import allowed_file from constants import ALLOWED_EXTENSIONS example_files = {"test.txt", "test.md", "test.exe"} for file in example_files: assert not allowed_file(filename=file, allowed_extensions=ALLOWED_EXTENSIONS)
def create_personal_area(token): data = json.loads(request.form['request']) if 'surname' in data and 'name' in data: if data['surname'] == '' or data['name'] == '': return {'error': 'Empty fields'}, 400 try: get_user = User.query.filter(User.token == token).one() except: return {'error': 'Personal_area not found'}, 401 check_personal_area = db.session.query(Personal_area).filter_by( id_user=get_user.id).first() if not check_personal_area: personal_area_schema = Personal_area_schema() data['id_user'] = get_user.id personal_area = personal_area_schema.load(data) db.session.add(personal_area) db.session.flush() id = personal_area.id user = User.query.get(get_user.id) user.have_personal_area = 1 db.session.add(user) image_schema = Images_personal_area_schema() if request.files.get('photo'): file = request.files.get('photo') if file and allowed_file(file.filename): filename = secure_filename(file.filename) extension = filename.split()[-1] new_filename = "upload-{}.{}".format(uuid4(), extension) file.save( os.path.join( current_app.config['UPLOAD_FOLDER_PERSONAL_AREA'], new_filename)) img_data = { "image_path": f'/images/personal_area/{new_filename}', "id_personal_area": id } db_image = image_schema.load(img_data) db.session.add(db_image) else: img_data = { "image_path": f'/images/default.jpg', "id_personal_area": id } db_image = image_schema.load(img_data) db.session.add(db_image) db.session.commit() return {'message': 'successfully!'}, 201 return {'error': 'Personal_area is already registered'}, 200 return {'error': 'Empty fields'}, 400
def update(id): auth_header = request.headers.get('Authorization') if auth_header: token = auth_header.split(" ")[1] else: return jsonify([{ 'status': 'failed', 'message': 'Not authorization header.' }]) decoded = decode_auth_token(token) user = User.get(User.id == decoded) journal_entry = JournalEntry.get(JournalEntry.id == id) if user and journal_entry: title = request.form.get('title') content = request.form.get('content') # check if request has file # if no new file uploaded, use current image_path if 'file' not in request.files: output = journal_entry.image_path else: file = request.files['file'] if file and allowed_file(file.filename): file.filename = secure_filename( str(user.id) + str(datetime.datetime.now()) + file.filename) output = upload_file_to_s3(file, 'journal-nyx') journal_entry.title = title journal_entry.content = content journal_entry.image_path = output if journal_entry.save(): return jsonify({ 'message': 'Successfully updated journal entry', 'status': 'success', 'journal': { 'id': journal_entry.id, 'created_at': journal_entry.created_at, 'updated_at': journal_entry.updated_at, 'user_id': journal_entry.user_id, 'title': journal_entry.title, 'content': journal_entry.content, 'image_path': journal_entry.image_path }, 'redirect': 'https://journal-nyx.herokuapp.com/journals/' }) else: errors = journal_entry.errors return jsonify([{'status': 'failed', 'message': errors}])
def post(): if request.method == "GET": return render_template("post.html") else: if not request.form.get("item"): return apology("Please provide an item name", 400) name = request.form.get("item") description = request.form.get("description") # http://flask.pocoo.org/docs/0.12/patterns/fileuploads/ if 'file' not in request.files: flash('No file part') return redirect("/post") file = request.files['file'] print(file) # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file') return redirect("/post") if file and allowed_file(file.filename): filename = file.filename extension = filename.split(".") now = str(datetime.datetime.now()) now = now.replace(" ", "") newfilename = now + "." + extension[1] file.save(os.path.join(app.config['UPLOAD_FOLDER'], newfilename)) # NEEDS FILE VALIDATION userid = session["user_id"] user = db.execute("SELECT * FROM users WHERE id = :userid", userid=userid) username = user[0]['username'] # Do you need these down here? #print(name) #print(filename) #print(username) #print(userid) db.execute( "INSERT INTO posted (name, image, username, userid, description) VALUES (:name, :newfilename, :username, :userid, :description)", name=name, newfilename=newfilename, username=username, userid=userid, description=description) db.execute("UPDATE users SET currency= :currency WHERE id= :id", currency=user[0]["currency"] + 1, id=userid) return redirect("/browse")
def post(self): if 'file' not in request.files: return{'error': 'No file uploaded'}, 403 file = request.files['file'] if allowed_file(file.filename): filename = secure_filename(file.filename) song = Songs(filename) file.save(app.config['UPLOAD_FOLDER'] + filename) db.session.add(song) db.session.commit() return {'success': 'File uploaded'}, 200 else: return {'error': 'File type is not allowed'}, 403
def test_allowed_file(mocker): extensions = set(['.png']) mocker.patch('helpers.ALLOWED_EXTENSIONS', extensions) assert helpers.allowed_file('test.png') assert helpers.allowed_file('test.PnG') assert not helpers.allowed_file('test.pdf') assert not helpers.allowed_file('this is just a string') assert not helpers.allowed_file(1234) assert not helpers.allowed_file(None) assert not helpers.allowed_file(dict())
def uploads(): if request.method == 'POST': dest_file_name = "" username = session["user_id"] dataCount = json.loads( requests.get(ref + '/user_data/' + username + "/datacount.json").text) if dataCount is None: dataCount = 0 else: dataCount = int(dataCount) heading = request.form.get("heading") image = request.files["image"] if image.filename == '': flash('No selected file') return redirect(request.url) if image and allowed_file(image.filename): filename = secure_filename(image.filename) dest_file_name = os.path.join(app.config['UPLOAD_FOLDER'], filename) image.save(dest_file_name) filename = session["user_id"] + str(dataCount) + filename os.rename(dest_file_name, os.path.join(app.config['UPLOAD_FOLDER'], filename)) dest_file_name = os.path.join(app.config['UPLOAD_FOLDER'], filename) imBlob = bucket.blob(dest_file_name) imBlob.upload_from_filename(dest_file_name) os.remove(os.path.join(dest_file_name)) desc = request.form.get("desc") ref2.child("user_data").child(username).child(str(dataCount)).set({ "impath": dest_file_name, "heading": heading, "desc": desc }) dataCount = dataCount + 1 ref2.child("user_data").child(username).update( {"datacount": dataCount}) return redirect(url_for("index")) return render_template("live.html")
def edit_post(post_id): # get post details from post_id parameter post = get_post(post_id) # query if request is posting to this route if request.method == "POST": # retrieve the image file object from the request form file = request.files['image'] # query file for correct formating if file and allowed_file(file.filename): # retrieve the filename of the file securely #avoiding cross-scripting filename = secure_filename(file.filename) # save file to local upload folder file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # connect to the database with engine.connect() as connection: # update query to insert new post to database s = posts.update().values( title=request.form.get("title"), location=request.form.get("location"), description=request.form.get("description"), image=filename, text=request.form.get("body"), date=datetime.datetime.now()).where(posts.c.id == post_id) connection.execute(s) else: # connect to the database with engine.connect() as connection: # update query to insert new post to database # given file form wasn't filled out by user s = posts.update().values( title=request.form.get("title"), location=request.form.get("location"), description=request.form.get("description"), text=request.form.get("body"), date=datetime.datetime.now()).where(posts.c.id == post_id) connection.execute(s) # show successful feedback to webpage flash("post updated") return redirect("/manage") else: return render_template("edit.html", post=post)
def ads(): if request.method == 'POST': symbol = request.form.get("symbol").upper() image = request.files["image"] if image.filename == '': flash('No selected file') return redirect(request.url) if image and allowed_file(image.filename): filename = secure_filename(image.filename) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) alttext = request.form.get("alttext") desc = request.form.get("desc") link = request.form.get("link") priority = request.form.get("priority") duration = request.form.get("duration") imagesource = "/static/images/" + image.filename try: db.execute("DELETE FROM advertisement WHERE symbol=:symbol", symbol=symbol) db.execute( "INSERT INTO advertisement(symbol,imagesource,alttext,description,link,priority,duration) VALUES (:symbol,:imagesource,:alttext,:description,:link,:priority,:duration)", symbol=symbol, imagesource=imagesource, alttext=alttext, description=desc, link=link, priority=priority, duration=duration) #Cost formula=300*priority+100*duration rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"]) money = rows[0]["cash"] #check balance if float(money) < float(priority * 300 + duration * 100): flash("Not enough money!") return render_template("ads.html") else: new_cash = money - (priority * 300 + duration * 100) db.execute("UPDATE users SET cash=:cash WHERE id=:user_id", cash=new_cash, user_id=session["user_id"]) except Exception as e: print(e) val = random_ads() ads1 = dict(list(val.items())[0:2]) ads2 = dict(list(val.items())[2:4]) ads3 = dict(list(val.items())[4:6]) return render_template("quote.html", ads1=ads1, ads2=ads2, ads3=ads3) return render_template("ads.html")
def myaccount(): users = sql_man.get_user_infomation(session["id"]) if request.method == "POST": name = request.form.get("username") email = request.form.get("email") password = request.form.get("password") confirmation = request.form.get("confirmation") old_password = request.form.get("oldpassword") # image = request.form("file") if password != confirmation: return apology("sorry password not match") if email: sql_man.update_user_email(email, session["id"]) flash("email changed") if name: sql_man.update_user_name(name, session["id"]) flash("name changed") hashee = sql_man.get_hash(session["id"]) if password: if len(hashee) != 1 or not check_password_hash( hashee[0]["hash"], request.form.get("oldpassword")): sql_man.update_user_password(password, session["id"]) flash("password changed") file = request.files['file'] if 'file' not in request.files: flash('No file part') return redirect(request.url) #if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file') return redirect("/myaccount") if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) image = file.filename sql_man.update_user_photo(image, session["id"]) flash("upload file") return redirect("/") # done. return render_template("myaccount.html", name=users[0]["username"], email=users[0]["email"], image=users[0]["image"])
def create_post(): required_fields = ['title', 'content'] post_data = {x:request.form[x] for x in required_fields} post = Post() post.set(post_data) upload_image = request.files['featured_image'] if upload_image.filename != '' and allowed_file(upload_image.filename): f = Attachment(upload_image.filename, data=upload_image.stream) post.set('featured_image', f) post.save() return redirect(url_for('show_post', post_id=post.id))
def upload_photo(): try: file = request.files["user_file"] except KeyError: flash("No file sent.") return redirect(request.url) extension = os.path.splitext(file.filename)[1] if not allowed_file(file.filename): flash("The extension of this file (%s) is not allowed." % extension) return redirect("/") if not file.filename: flash("Please select a file.") return redirect("/") file.filename = random_string(16) + extension file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) file_path = os.path.join(app.config['UPLOAD_FOLDER'] + "/" + file.filename) bytessize, width, height, exif = get_image_properties(file_path) datetime_original = exif.get('DateTimeOriginal', None) if datetime_original: datetime_original = datetime.datetime.strptime( datetime_original, '%Y:%m:%d %H:%M:%S' ) datetime_original = datetime_original.strftime("%Y-%m-%d %H:%M:%S") else: flash("This photo is not dated. We assumed is today.") user_id = flask_login.current_user.get_id() url = upload_file_to_s3(file_path, 'users/%s/%s' % (user_id, file.filename), file.content_type, app.config["S3_BUCKET"]) now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") cur = get_db().execute(""" insert into photos (object, dt_uploaded, dt,original_name, bytessize, width, height, user_id) values (?,?,?,?,?,?,?,?)""", (url, now, datetime_original or now, file.filename, bytessize, width, height, flask_login.current_user.get_id(),)) g._database.commit() cur.close() os.remove(file_path) return redirect("/")
def update_charities(token, id): get_user = User.query.filter(User.token == token).one() #if get_user.username == 'Admin' or get_user.username == 'admin': try: charities = Charities.query.get(id) except: return {'error': 'Charities not found'}, 401 if request.form: data = json.loads(request.form['charities']) data['id'] = id сharities_schema = Charities_schema() charities = сharities_schema.load(data=json.dumps(data), many=True) db.session.add(charities) db.session.commit() try: image_schema = Images_charities_schema() file = request.files.get('photo') if file and allowed_file(file.filename): get_photo = db.session.query(Images_charities).filter_by( id_charities=id).first() if get_photo: photo = Images_charities.query.get(get_photo.id) db.session.delete(photo) if photo.image_path != '/images/default.jpg': path_delete = current_app.config[ 'PROJECT_HOME'] + photo.image_path os.remove(path_delete) db.session.commit() filename = secure_filename(file.filename) extension = filename.split()[-1] new_filename = "upload-{}.{}".format(uuid4(), extension) file.save( os.path.join(current_app.config['UPLOAD_FOLDER_CHARITIES'], new_filename)) img_data = { "image_path": f'/images/charities/{new_filename}', "id_charities": id } db_image = image_schema.load(img_data) db.session.add(db_image) except: return {'message': 'error edit photo'}, 401 db.session.commit() return {'message': 'successfully!'}, 201
def myaudio(): now = datetime.datetime.now() if request.method == 'POST': # Checks if the post request has the file part if 'file' not in request.files: flash('No file part.') return redirect(request.url) file = request.files['file'] # If user does not select file, browser also # submits an empty part without filename if file.filename == '': flash('Please select a file.') return redirect(request.url) # Saves file to the input folder in audio2midi if file and allowed_file(file.filename): filename = secure_filename(file.filename) songname = filename.split('.wav')[0] file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) main('./audio2midi/input/' + filename, './audio2midi/model/model_melody', './audio2midi/output/' + songname) os.chdir("./audio2midi/output") subprocess.check_call([ os.environ['Muse'], "-o", songname + ".musicxml", songname + ".mid" ]) os.chdir("./../..") # Enters .wav file into a database for each user to keep track of saved audio files. db.execute( "INSERT INTO audio (user_id, audio_url, time) VALUES (?, ?, ?)", session['user_id'], file.filename, now.strftime("%Y-%m-%d %H:%M:%S")) return redirect("/render") else: # Error checking for non-wav files. flash("Please select a .wav file.") return redirect("/myaudio") else: # If page reached via GET, displays table of saved audio tracks rows = db.execute("SELECT * FROM audio WHERE user_id = ?", session['user_id']) filtered_rows = [] [filtered_rows.append(row) for row in rows if row not in filtered_rows] return render_template("myaudio.html", rows=filtered_rows, id=session['user_id'])
def create(): user = User.get_by_id(current_user.id) username = user.username file = request.files.get('upload_pic') if "upload_pic" not in request.files or file.filename == "": flash('Please select a picture for upload') if file and helpers.allowed_file(file.filename): file.filename = secure_filename(f"feed_{str(datetime.datetime.now())}_{file.filename}") output = helpers.upload_file_to_s3(file, Config.S3_BUCKET) Image.create(user_id=current_user.id, image_url=file.filename) return redirect(url_for('users.show', username=username)) else: return redirect(url_for('users.show', username=username))
def edit(item_id): """lets the user edit his currently selling items""" # get the item to edit from database. item_to_edit = Item.query.get(item_id) # if no such item return error message. if not item_to_edit: return render_template("mes.html", error="page not found") # if item doesn't belong to this user return error message. if item_to_edit.user_id != session['user_id']: return render_template("mes.html", \ error="you don't own the item that you are trying to edit") # if request.method == "GET" return edit page. if request.method == "GET": return render_template("edit.html", item=item_to_edit, categories=app.config['CATEGORIES']) # else if request.method == "GET" # if the user didn't provide a new image the just update the item. if not request.files['photo']: item_to_edit.title = request.form.get("title") item_to_edit.price = request.form.get("price") item_to_edit.description = request.form.get("description") item_to_edit.category = request.form.get("category") # else if the user provided a new image delete the old one. else: os.remove("%s/%s" % (app.config['UPLOAD_FOLDER'], item_to_edit.photo)) photo = request.files['photo'] file_name = "" # if photo is valid then save it and add the name to the database. if photo and allowed_file(photo.filename): file_name = "%d.%s" % (uuid.uuid4(), photo.filename.rsplit( '.', 1)[1].lower()) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name)) item_to_edit.title = request.form.get("title") item_to_edit.price = request.form.get("price") item_to_edit.description = request.form.get("description") item_to_edit.category = request.form.get("category") item_to_edit.photo = file_name # commit changes on the database. db.session.commit() # let the user know that the item was updated. flash('item edited successfully') return redirect(url_for("currentsellings"))
def upload(): if request.method == 'POST': # Check if there is a file part if 'imagefile' not in request.files: flash('No file part') return render_template('upload.html') image_file = request.files['imagefile'] # Check if there is a selected file if image_file.filename == '': flash('No selected file') return render_template('upload.html') # Check if file type is allowed if not allowed_file(image_file.filename): flash('file type not supported') return render_template('upload.html') if image_file: # Rename extension = image_file.filename.rsplit('.', 1)[1].lower() filename = "{}.{}".format(hash(datetime.now().timestamp()), extension) # Save file path = os.path.join(app.config['UPLOAD_FOLDER'], filename) image_file.save(path) image_file.close() # Process file color = request.form.get('imagebgcolor') color = Color(color) imgpro.centerSquareCrop(path) imgpro.asciiArt(path, path, bg=color.get_rgb()) # Save filename and owner to database conn = sqlite3.connect(DATABASE_NAME) db = conn.cursor() db.execute( "INSERT INTO images(user_rowid, filename) VALUES (?, ?);", (session['user_id'], filename)) conn.commit() conn.close() # Redirect to browse return redirect('/') flash('unknown error') return render_template('upload.html')
def upload_file(index, type_upload): """ """ if not 'file_upload_' + index in request.files: return '' file = request.files['file_upload_' + index] if len(file.filename) < 2: return '' name = file.filename.rsplit('.', 1)[0] extension = file.filename.rsplit('.', 1)[1] name = str(int(time.time())) + '_' + index + '_' + name + '.' + extension name = name.lower() if file and allowed_file(name): path_upload = UP_FOLDER + type_upload + '/' file.save(os.path.join(path_upload, name)) image_path = type_upload + '/' + name return image_path else: return 'error1'
def upload_file(index, type_upload): """ """ if not 'file_upload_'+index in request.files: return '' file = request.files['file_upload_'+index] if len(file.filename) < 2: return '' name = file.filename.rsplit('.', 1)[0] extension = file.filename.rsplit('.', 1)[1] name = str(int(time.time())) + '_' + index + '_' + name + '.' + extension name = name.lower() if file and allowed_file(name): path_upload = UP_FOLDER + type_upload + '/' file.save(os.path.join(path_upload, name)) image_path = type_upload + '/' + name return image_path else: return 'error1'
def upload_image(request, image_id, type): if 'file' not in request.files: flash('No file part') # return redirect(request.url) return False file = request.files['file'] if file.filename == '': flash('No image selected for uploading') # return redirect(request.url) return False if file and allowed_file(file.filename): filename = secure_filename(str(image_id) + '.jpg') file.save(os.path.join(app.config[type], filename)) #file.save(filename) #print('upload_image filename: ' + filename) #flash('Image successfully uploaded.') # return render_template('index.html') return True else: flash('Allowed image types are -> png, jpg, jpeg, gif') return False # return redirect(request.url)
def upload_file(): if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) freq = float(request.form['freq']) duration = float(request.form['duration']) vol_song = (int(request.form['vol_song']))/100 vol_click = (int(request.form['vol_click']))/100 retFile = generate_click(file, filename, freq, duration, vol_song, vol_click, app.config['CONVERT_FOLDER']) return redirect(url_for('return_file', filename = retFile)) return render_template('home.html')
def generateFull(): if 'audioFile' not in request.files: return render_template("noAudioFile.html"), 400 file = request.files['audioFile'] if file and allowed_file(file.filename): click_freq = request.args.get("click_freq") click_dur = request.args.get("click_dur") if click_freq is None or click_dur is None: return render_template('error.html'), 400 saveName = generate_click(file, file.filename, float(click_freq), float(click_dur), 1, 1, app.config['CONVERT_FOLDER']) response = make_response(send_file(os.path.join(app.config['CONVERT_FOLDER'], saveName), attachment_filename = "converted.wav", as_attachment = True)) return response, 200 else: return render_template('badFileType.html'), 400
def create_enter(): if 'username' not in session: return redirect(url_for('catalog.login')) form = UserForm(request.form) choices = list() want_participate_box = Classifier.query.filter_by(category='want_participate').all() for want_participate_box in want_participate_box: if want_participate_box: choices.append((want_participate_box.tag_lv,want_participate_box.tag_lv)) form.want_participate.choices = choices choices = [] city_box = Classifier.query.filter_by(category='city').all() for city_box in city_box: if city_box: choices.append((city_box.tag_lv,city_box.tag_lv)) form.city.choices = choices choices = [] haircolor = Classifier.query.filter_by(category='haircolor').all() for haircolor in haircolor: if haircolor: choices.append((haircolor.tag_lv,haircolor.tag_lv)) form.haircolor.choices = choices choices = [] eyecolor = Classifier.query.filter_by(category='eyecolor').all() for eyecolor in eyecolor: if eyecolor: choices.append((eyecolor.tag_lv,eyecolor.tag_lv)) form.eyecolor.choices = choices choices = [] voice = Classifier.query.filter_by(category='voice').all() for voice in voice: if voice: choices.append((voice.tag_lv,voice.tag_lv)) form.voice.choices = choices choices = [] co = Classifier.query.filter_by(category='current_occupation').all() for co in co: if co: choices.append((co.tag_lv,co.tag_lv)) form.current_occupation.choices = choices choices = [] for size in range(35,50,1): # filled clothe size range 35 to 49 choices.append((str(size),(str(size)))) form.foot_size.choices = choices choices = [] for size in range(32,69,2): # filled clothe size range 32 to 68 choices.append((str(size),(str(size)))) form.cloth_size.choices = choices if form.validate_on_submit(): name = form.name.data surname = form.surname.data nickname = form.nickname.data pcode = form.pcode.data contract_nr = form.contract_nr.data birthdate = form.birthdate.data my_phone_code = form.my_phone_code.data my_phone = form.my_phone.data email = form.email.data other_phone_code = form.other_phone_code.data other_phone = form.other_phone.data home_address = form.home_address.data height = form.height.data foot_size = form.foot_size.data cloth_size = form.cloth_size.data voice = form.voice.data contact_lenses = form.contact_lenses.data be_dressed = form.be_dressed.data species = form.species.data mother_phone_code = form.mother_phone_code.data mother_phone = form.mother_phone.data mother_name = form.mother_name.data father_phone_code = form.father_phone_code.data father_phone = form.father_phone.data father_name = form.father_name.data speciality = form.speciality.data experience = form.experience.data city = form.city.data haircolor = form.haircolor.data eyecolor = form.eyecolor.data current_occupation = form.current_occupation.data workplace = form.workplace.data cb_tags = form.cb_tags.data family_notes = form.family_notes.data play_age_from = form.play_age_from.data play_age_to = form.play_age_to.data person = Person(datetime.datetime.now(pytz.timezone("Europe/Riga")), datetime.datetime.now(pytz.timezone("Europe/Riga")), name, surname, nickname, pcode, contract_nr, birthdate, my_phone_code, my_phone, email, other_phone_code, other_phone, home_address, height, foot_size, cloth_size, voice, contact_lenses, be_dressed, None, False, species, mother_phone_code, mother_phone, mother_name, father_phone_code, father_phone, father_name, speciality, experience, None, current_occupation, workplace, play_age_from, play_age_to) db.session.add(person) db.session.commit() skills = list() if city: skills.append(['city', city]) if haircolor: skills.append(['haircolor', haircolor]) if eyecolor: skills.append(['eyecolor', eyecolor]) for subspeciality in form.subspeciality.data: skills.append(['subspeciality', subspeciality]) for danceskill in form.danceskill.data: skills.append(['danceskill', danceskill]) for singskill in form.singskill.data: skills.append(['singskill', singskill]) for musicskill in form.musicskill.data: skills.append(['musicskill', musicskill]) for sportskill in form.sportskill.data: skills.append(['sportskill', sportskill]) for swimskill in form.swimskill.data: skills.append(['swimskill', swimskill]) for otherskill in form.otherskill.data: skills.append(['otherskill', otherskill]) for driveskill in form.driveskill.data: skills.append(['driveskill', driveskill]) for languageskill in form.languageskill.data: skills.append(['languageskill', languageskill]) for want_participate in form.want_participate.data: skills.append(['want_participate', want_participate]) for dont_want_participate in form.dont_want_participate.data: skills.append(['dont_want_participate', dont_want_participate]) for interested_in in form.interested_in.data: skills.append(['interested_in', interested_in]) for tattoo in form.tattoo.data: skills.append(['tattoo', tattoo]) for piercing in form.piercing.data: skills.append(['piercing', piercing]) for afraidof in form.afraidof.data: skills.append(['afraidof', afraidof]) for religion in form.religion.data: skills.append(['religion', religion]) for educational_institution in form.educational_institution.data: skills.append(['educational_institution', educational_institution]) for learned_profession in form.learned_profession.data: skills.append(['learned_profession', learned_profession]) for degree in form.degree.data: skills.append(['degree', degree]) for cb_tags in form.cb_tags.data: skills.append(['cb_tags', cb_tags]) for family_notes in form.family_notes.data: skills.append(['family_notes', family_notes]) for skill in skills: #flash('Skills [%s] [%s]' % (skill[0], skill[1]), 'success') item = Classifier.query.filter_by(category=skill[0], tag_lv = skill[1].capitalize()).first() if item is None: # add new entry in Classifier item = Classifier(category=skill[0], tag_lv=skill[1].capitalize()) db.session.add(item) db.session.commit() add_skill = Skill(person=person, classifier=item) db.session.add(add_skill) db.session.commit() file_mask = helpers.make_file_mask(species, birthdate, speciality, height) files = request.files.getlist('images[]') for file in files: #flash('file: [%s]' % file.filename, 'success') filename = '' if file and allowed_file(file.filename): filename = str(person.id) + "_" + file_mask + secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) add_document = Document(datetime.datetime.now(pytz.timezone("Europe/Riga")), person.id, 'photo', filename) db.session.add(add_document) #helpers.file_upload('photo', 'image1', person.id) #helpers.file_upload('photo', 'image2', person.id) helpers.file_upload('audio', 'audio', person.id) helpers.file_upload('video', 'video', person.id) profile_image = request.files['profile_image'] cv = request.files['cv'] filename = '' if profile_image and helpers.allowed_file(profile_image.filename): #flash('profile_image: [%s]' % profile_image, 'success') filename, file_extension = os.path.splitext(secure_filename(profile_image.filename)) filename = str(person.id) + "_profile" + file_extension profile_image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) Person.query.filter_by(id=person.id).update({ 'profile_image': filename }) if cv and helpers.allowed_file(cv.filename): #flash('profile_image: [%s]' % profile_image, 'success') filename, file_extension = os.path.splitext(secure_filename(cv.filename)) filename = str(person.id) + "_cv" + file_extension cv.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) Person.query.filter_by(id=person.id).update({ 'cv': filename }) db.session.commit() flash( 'The person %s has been created' % person.id, 'success' ) return redirect( url_for('catalog.profiles') ) if form.errors: flash(form.errors, 'danger') return render_template('data-enter.html', form=form)
def update_profile(id): if 'username' not in session: return redirect(url_for('catalog.login')) person = Person.query.get_or_404(id) form = UpdateForm( request.form, name=person.name, surname=person.surname, nickname=person.nickname, pcode=person.pcode, contract_nr=person.contract_nr, birthdate=person.birthdate, my_phone=person.my_phone, email=person.email, other_phone=person.other_phone, home_address=person.home_address, height=person.height, foot_size=person.foot_size, cloth_size=person.cloth_size, voice=person.voice, contact_lenses=person.contact_lenses, be_dressed=person.be_dressed, mother_phone_code=person.mother_phone_code, mother_phone=person.mother_phone, mother_name=person.mother_name, father_phone_code=person.father_phone_code, father_phone=person.father_phone, father_name=person.father_name, experience=person.experience, current_occupation = person.current_occupation, workplace = person.workplace, play_age_from = person.play_age_from, play_age_to = person.play_age_to ) if person.species: form.species.data=person.species if person.speciality: form.speciality.data=person.speciality # Get all possible values(choices) from Classifier choices = list() city_box = Classifier.query.filter_by(category='city').all() for city_box in city_box: if city_box: choices.append((city_box.tag_lv,city_box.tag_lv)) form.city.choices = choices choices = [] haircolor = Classifier.query.filter_by(category='haircolor').all() for haircolor in haircolor: if haircolor: choices.append((haircolor.tag_lv,haircolor.tag_lv)) form.haircolor.choices = choices choices = [] eyecolor = Classifier.query.filter_by(category='eyecolor').all() for eyecolor in eyecolor: if eyecolor: choices.append((eyecolor.tag_lv,eyecolor.tag_lv)) form.eyecolor.choices = choices choices = [] voice = Classifier.query.filter_by(category='voice').all() for voice in voice: if voice: choices.append((voice.tag_lv,voice.tag_lv)) form.voice.choices = choices choices = [] co = Classifier.query.filter_by(category='current_occupation').all() for co in co: if co: choices.append((co.tag_lv,co.tag_lv)) form.current_occupation.choices = choices choices = [] for size in range(35,50,1): # filled clothe size range 35 to 49 choices.append((str(size),(str(size)))) form.foot_size.choices = choices choices = [] for size in range(32,69,2): # filled clothe size range 32 to 68 choices.append((str(size),(str(size)))) form.cloth_size.choices = choices # Get all assigned Skills for person and add them as selected in form. classifiers = Classifier.query.select_from(join(Classifier, Skill)).filter(Skill.person_id == id) skill_box = {} for item in classifiers: #flash('skill [%s] cat [%s] ' % (item.tag_lv, item.category), 'info') if skill_box.get(item.category) is None: skill_box[item.category] = [(item.tag_lv,item.tag_lv)] else: skill_box[item.category].append((item.tag_lv,item.tag_lv)) #flash('danceskilldanceskill [%s]' % skill_box.get('danceskill'), 'info') if skill_box.get('city'): for skill in skill_box.get('city'): form.city.data= skill[0] if skill_box.get('haircolor'): for skill in skill_box.get('haircolor'): form.haircolor.data= skill[0] if skill_box.get('eyecolor'): for skill in skill_box.get('eyecolor'): form.eyecolor.data= skill[0] if skill_box.get('subspeciality'): form.subspeciality.choices = skill_box.get('subspeciality') if skill_box.get('danceskill'): form.danceskill.choices = skill_box.get('danceskill') if skill_box.get('singskill'): form.singskill.choices = skill_box.get('singskill') if skill_box.get('musicskill'): form.musicskill.choices = skill_box.get('musicskill') if skill_box.get('sportskill'): form.sportskill.choices = skill_box.get('sportskill') if skill_box.get('swimskill'): form.swimskill.choices = skill_box.get('swimskill') if skill_box.get('driveskill'): form.driveskill.choices = skill_box.get('driveskill') if skill_box.get('languageskill'): form.languageskill.choices = skill_box.get('languageskill') if skill_box.get('otherskill'): form.otherskill.choices = skill_box.get('otherskill') if skill_box.get('want_participate'): form.want_participate.choices = skill_box.get('want_participate') if skill_box.get('dont_want_participate'): form.dont_want_participate.choices = skill_box.get('dont_want_participate') if skill_box.get('interested_in'): form.interested_in.choices = skill_box.get('interested_in') if skill_box.get('tattoo'): form.tattoo.choices = skill_box.get('tattoo') if skill_box.get('piercing'): form.piercing.choices = skill_box.get('piercing') if skill_box.get('afraidof'): form.afraidof.choices = skill_box.get('afraidof') if skill_box.get('religion'): form.religion.choices = skill_box.get('religion') if skill_box.get('educational_institution'): form.educational_institution.choices = skill_box.get('educational_institution') if skill_box.get('learned_profession'): form.learned_profession.choices = skill_box.get('learned_profession') if skill_box.get('degree'): form.degree.choices = skill_box.get('degree') if skill_box.get('current_occupation'): form.current_occupation.choices = skill_box.get('current_occupation') if skill_box.get('voice'): form.current_occupation.choices = skill_box.get('voice') if skill_box.get('cb_tags'): form.cb_tags.choices = skill_box.get('cb_tags') if skill_box.get('family_notes'): form.family_notes.choices = skill_box.get('family_notes') photos = Document.query.filter_by(person_id=id, type='photo').paginate(1,100,error_out=False) videos = Document.query.filter_by(person_id=id, type='video').paginate(1,100,error_out=False) #for photo in photos: # flash("photo : [%s]" % photo.name, 'info') if form.validate_on_submit(): name = form.name.data surname = form.surname.data nickname = form.nickname.data pcode = form.pcode.data contract_nr = form.contract_nr.data birthdate = form.birthdate.data my_phone = form.my_phone.data email = form.email.data other_phone = form.other_phone.data home_address = form.home_address.data height = form.height.data foot_size = request.form['foot_size'] cloth_size = request.form['cloth_size'] voice = request.form['voice'] contact_lenses = form.contact_lenses.data be_dressed = form.be_dressed.data # field is set from request.form['species'], because form.species.data is alredy set to (old)value from db species = request.form['species'] mother_phone_code = form.mother_phone_code.data mother_phone = form.mother_phone.data mother_name = form.mother_name.data father_phone_code = form.father_phone_code.data father_phone = form.father_phone.data father_name = form.father_name.data speciality = request.form['speciality'] experience = form.experience.data city = request.form['city'] haircolor = request.form['haircolor'] eyecolor = request.form['eyecolor'] current_occupation = request.form['current_occupation'] workplace = form.workplace.data play_age_from = form.play_age_from.data play_age_to = form.play_age_to.data Person.query.filter_by(id=id).update({ 'modified': datetime.datetime.now(pytz.timezone("Europe/Riga")), 'name': name, 'surname': surname, 'nickname': nickname, 'pcode': pcode, 'contract_nr': contract_nr, 'birthdate': birthdate, 'my_phone': my_phone, 'email': email, 'other_phone': other_phone, 'home_address': home_address, 'height': height, 'foot_size': foot_size, 'cloth_size': cloth_size, 'voice': voice, 'contact_lenses': contact_lenses, 'be_dressed': be_dressed, 'species': species, 'mother_phone_code': mother_phone_code, 'mother_phone': mother_phone, 'mother_name': mother_name, 'father_phone_code': father_phone_code, 'father_phone': father_phone, 'father_name': father_name, 'speciality': speciality, 'experience': experience, 'current_occupation': current_occupation, 'workplace': workplace, 'play_age_from': play_age_from, 'play_age_to': play_age_to }) skills = list() if city: skills.append(['city', city]) if haircolor: skills.append(['haircolor', haircolor]) if eyecolor: skills.append(['eyecolor', eyecolor]) for subspeciality in form.subspeciality.data: skills.append(['subspeciality', subspeciality]) for danceskill in form.danceskill.data: skills.append(['danceskill', danceskill]) for singskill in form.singskill.data: skills.append(['singskill', singskill]) for musicskill in form.musicskill.data: skills.append(['musicskill', musicskill]) for sportskill in form.sportskill.data: skills.append(['sportskill', sportskill]) for swimskill in form.swimskill.data: skills.append(['swimskill', swimskill]) for otherskill in form.otherskill.data: skills.append(['otherskill', otherskill]) for driveskill in form.driveskill.data: skills.append(['driveskill', driveskill]) for languageskill in form.languageskill.data: skills.append(['languageskill', languageskill]) for want_participate in form.want_participate.data: skills.append(['want_participate', want_participate]) for dont_want_participate in form.dont_want_participate.data: skills.append(['dont_want_participate', dont_want_participate]) for interested_in in form.interested_in.data: skills.append(['interested_in', interested_in]) for tattoo in form.tattoo.data: skills.append(['tattoo', tattoo]) for piercing in form.piercing.data: skills.append(['piercing', piercing]) for afraidof in form.afraidof.data: skills.append(['afraidof', afraidof]) for religion in form.religion.data: skills.append(['religion', religion]) for educational_institution in form.educational_institution.data: skills.append(['educational_institution', educational_institution]) for learned_profession in form.learned_profession.data: skills.append(['learned_profession', learned_profession]) for degree in form.degree.data: skills.append(['degree', degree]) for cb_tags in form.cb_tags.data: skills.append(['cb_tags', cb_tags]) for family_notes in form.family_notes.data: skills.append(['family_notes', family_notes]) # Delete outdated skills Skill.query.filter_by(person_id=id).delete() for skill in skills: #flash('Skills [%s] [%s]' % (skill[0], skill[1]), 'success') item = Classifier.query.filter_by(category=skill[0], tag_lv = skill[1].capitalize()).first() if item is None: # add new entry in Classifier item = Classifier(category=skill[0], tag_lv=skill[1].capitalize()) db.session.add(item) add_skill = Skill(person=person, classifier=item) db.session.add(add_skill) db.session.commit() file_mask = helpers.make_file_mask(species, birthdate, speciality, height) files = request.files.getlist('images[]') for file in files: #flash('file: [%s]' % file.filename, 'success') filename = '' if file and allowed_file(file.filename): filename = str(person.id) + "_" + file_mask + secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) add_document = Document(datetime.datetime.now(pytz.timezone("Europe/Riga")), person.id, 'photo', filename) db.session.add(add_document) #helpers.file_upload('photo', 'image1', person.id) #helpers.file_upload('photo', 'image2', person.id) #helpers.file_upload('photo', 'image3', person.id) #helpers.file_upload('photo', 'image4', person.id) #helpers.file_upload('photo', 'image5', person.id) helpers.file_upload('audio', 'audio', person.id) helpers.file_upload('video', 'video', person.id) profile_image = request.files['profile_image'] cv = request.files['cv'] filename = '' if profile_image and helpers.allowed_file(profile_image.filename): #flash('profile_image: [%s]' % profile_image, 'success') filename, file_extension = os.path.splitext(secure_filename(profile_image.filename)) filename = str(person.id) + "_profile" + file_extension profile_image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) Person.query.filter_by(id=person.id).update({ 'profile_image': filename }) if cv and helpers.allowed_file(cv.filename): #flash('profile_image: [%s]' % profile_image, 'success') filename, file_extension = os.path.splitext(secure_filename(cv.filename)) filename = str(person.id) + "_cv" + file_extension cv.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) Person.query.filter_by(id=person.id).update({ 'cv': filename }) db.session.commit() flash('Profile updated.', 'info') return redirect(url_for('catalog.profiles')) if form.errors: flash(form.errors, 'danger') return render_template('profile_update.html', form=form, person=person, photos=photos, videos=videos )