Skip to content

Instantly share code, notes, and snippets.

@batok
Created July 7, 2010 14:09
Show Gist options
  • Save batok/466738 to your computer and use it in GitHub Desktop.
Save batok/466738 to your computer and use it in GitHub Desktop.
import os, glob
from flask import Flask, request, redirect, url_for, render_template
from werkzeug import SharedDataMiddleware
from werkzeug import secure_filename
import subprocess
from subprocess import check_output, CalledProcessError
from bdata import UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/uploads': UPLOAD_FOLDER
})
app.add_url_rule('/uploads/<filename>', 'uploaded_file',
build_only=True)
def allowed_file(filename):
return "." in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route("/", methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
#app.logger.debug("A valid file {}".format( file.filename))
filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
command_line = "/usr/bin/montage +frame +shadow +label -tile 10x3 -geometry 50x50+0+0 {0}/*.jpg {0}/mosaic.png".format(UPLOAD_FOLDER)
#app.logger.debug(command_line)
command_list = command_line.split(" ")
try:
output = check_output( command_list)
print output
except CalledProcessError,e:
return e.output
return redirect(url_for('uploaded_file',
filename=filename))
else:
return "Invalid file"
return '''
<!doctype html>
<title>Upload an image file</title>
<h1>Upload an image file</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<hr/>
<a href="{}">List Files</a>
'''.format( url_for("listfiles2"))
@app.route("/listfiles")
def lfiles():
lf = []
for fname in glob.glob("{}/*".format(UPLOAD_FOLDER)):
row = "<tr><td>{}</td><td align='right'>{:,d}</td></tr>".format(fname.split("/")[-1], os.stat(fname).st_size)
lf.append(row)
return '''
<!doctype html>
<title>List Upload Directory</title>
<h1>Upload Directory</h1>
<table>
<tr><td>Name</td><td>Size</td></tr>
{}
</table>
'''.format("\n".join(lf))
@app.route("/listfiles2")
def lfiles2():
lf = []
for fname in sorted(glob.glob("{}/*".format(UPLOAD_FOLDER))):
lf.append((fname.split("/")[-1],"{:,d}".format(os.stat(fname).st_size)))
return render_template( "listfiles.html", lf = lf )
if __name__ == "__main__":
app.run(debug = True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment