Last active
August 29, 2015 14:25
-
-
Save fenimore/7f5a0226e6f5badb31c4 to your computer and use it in GitHub Desktop.
flask-photo-manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from flask import Flask, request, redirect, url_for, render_template, send_from_directory | |
from werkzeug import secure_filename | |
# initialization | |
app = Flask(__name__) | |
UPLOAD_FOLDER = os.path.join(app.root_path, 'uploads') | |
ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg']) | |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
app.config.update( | |
DEBUG = True, | |
) | |
# methods | |
def allowed_file(filename): | |
return '.' in filename and \ | |
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS | |
# controllers | |
@app.route('/') | |
@app.route('/index') | |
def index(): | |
user = {'nickname':'Fen'} # mock user | |
albums = [ | |
{ | |
'name':'France', | |
'image':'Nice' | |
}, | |
{ | |
'name':'Bejing', | |
'image':'Wooo' | |
} | |
] | |
return render_template('index.html', title='Home', albums=albums, user=user) | |
@app.route('/upload', methods=['GET', 'POST']) | |
def upload(): | |
if request.method == 'POST': | |
file = request.files['file'] | |
if file and allowed_file(file.filename): | |
filename = secure_filename(file.filename) | |
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) | |
return redirect(url_for('uploaded_file', filename=filename)) | |
return ''' | |
<!doctype html> | |
<title>Upload new File</title> | |
<h1>Upload new File</h1> | |
<form action="" method=post enctype=multipart/form-data> | |
<p><input type=file name=file> | |
<input type=submit value=Upload> | |
</form> | |
''' | |
# This route is expecting a parameter containing the name | |
# of a file. Then it will locate that file on the upload | |
# directory and show it on the browser, so if the user uploads | |
# an image, that image is going to be show after the upload | |
@app.route('/uploads/<filename>') | |
def uploaded_file(filename): | |
return send_from_directory(app.config['UPLOAD_FOLDER'], | |
filename) | |
# launch | |
if __name__ == "__main__": | |
port = int(os.environ.get("PORT", 5000)) | |
app.run(host='0.0.0.0', port=port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment