Skip to content

Instantly share code, notes, and snippets.

@rminderhoud
Last active July 27, 2017 01:06
Show Gist options
  • Save rminderhoud/c212bc51ae4bb484dbf4709d6ea59b4c to your computer and use it in GitHub Desktop.
Save rminderhoud/c212bc51ae4bb484dbf4709d6ea59b4c to your computer and use it in GitHub Desktop.
Flask basic upload
""" Basic file upload example for Flask
Example provided for spitfiredd on thread
https://www.reddit.com/r/flask/comments/5zen73/help_looking_to_create_a_simple_web_app_where_i/?ref=share&ref_source=link
"""
from flask import Flask, request, render_template, send_file
app = Flask(__name__)
# We need a secret key to work with form data
# http://flask.pocoo.org/docs/0.12/config/#builtin-configuration-values
app.config['SECRET_KEY'] = 'super secret'
@app.route('/', methods=['GET', 'POST'])
def index():
# The browser sends an HTTP GET when opening a page
# so we respond with some HTML to display our page
if request.method == 'GET':
return '''<!DOCTYPE html>
<html>
<head><title>Upload</title></head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file1" />
<input type="file" name="file2" />
</form>
</body>
</html>'''
elif request.method == 'POST':
# Get our files from the request object (or None if
# there is no file
file1 = request.files.get('file1', None)
file2 = request.files.get('file2', None)
# Check if files exist
files_exist = file1 != None and file2 != None
files_name = file1.filename != '' and file2.filename != ''
# Return error if they don't
if not (files_exist and files_named):
flash('Please select two files')
return redirect(request.url)
# Do processing here (e.g. load into pandas)
#
# NOTE: If you are saving the files with the original name
# make sure to sanitize it first
#
# Example (http://xlsxwriter.readthedocs.io/working_with_pandas.html#saving-the-dataframe-output-to-a-string):
import io
import pandas as pd
d = pd.DataFrame()
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xslxwriter')
d.to_excel(writer, sheet_name='Sheet1')
writer.save()
return send_file(output, attachment_filename='output.xslx', as_attachment=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment