Created
January 16, 2019 12:44
-
-
Save resurrexi/cc4c069572c4607edc5953202ccf2d0a to your computer and use it in GitHub Desktop.
serving a temporary zip file from a directory in flask
This file contains hidden or 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 | |
| import zipfile | |
| import tempfile | |
| from flask import Flask, render_template, request, Response | |
| from datetime import datetime | |
| from string import Template | |
| FILEPATH = os.path.dirname(os.path.realpath(__file__)) | |
| TEMPLATE_FOLDER = os.path.join(FILEPATH, "templates") | |
| TEMP_FOLDER = os.path.join(FILEPATH, "temp") | |
| SCRIPTS_FOLDER = os.path.join(FILEPATH, "scripts") | |
| app = Flask(__name__) | |
| app.config['TEMPLATE_FOLDER'] = TEMPLATE_FOLDER | |
| app.config['SCRIPTS_FOLDER'] = SCRIPTS_FOLDER | |
| app.secret_key = 'DDD' | |
| def walk_and_zip(dir, zf, build, from_ts, crumbs=list()): | |
| for obj in os.listdir(dir): | |
| if os.path.isdir(os.path.join(dir, obj)): | |
| if obj.startswith("hunter_cheatdata_parse_"): | |
| crumb = obj + '_' + build | |
| else: | |
| crumb = obj | |
| walk_and_zip( | |
| os.path.join(dir, obj), | |
| zf, | |
| build, | |
| from_ts, | |
| crumbs + [crumb] | |
| ) | |
| elif os.path.isfile(os.path.join(dir, obj)): | |
| with open(os.path.join(dir, obj)) as f_read: | |
| raw_query = Template(f_read.read()) | |
| query = raw_query.safe_substitute( | |
| build=build, | |
| from_ts=from_ts | |
| ) | |
| zf.writestr('{}\\{}'.format('\\'.join(crumbs), obj), query) | |
| @app.context_processor | |
| def inject_now(): | |
| return {'now': datetime.utcnow()} | |
| @app.route('/') | |
| @app.route('/index') | |
| def index(): | |
| return render_template('index.html') | |
| @app.route('/export', methods=['GET', 'POST']) | |
| def build_exports(): | |
| if request.method == 'POST': | |
| build = request.form['build'] | |
| from_ts = request.form['from_ts'] | |
| with tempfile.SpooledTemporaryFile() as tmp: | |
| # create zip file | |
| zipf = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) | |
| # read exports and add to zip file | |
| walk_and_zip( | |
| app.config['SCRIPTS_FOLDER'], | |
| zipf, | |
| build, | |
| from_ts | |
| ) | |
| # close zip file | |
| zipf.close() | |
| tmp.seek(0) | |
| return Response(tmp.read(), | |
| mimetype='application/x-zip-compressed') | |
| return render_template('export.html') | |
| if __name__ == '__main__': | |
| from waitress import serve | |
| serve(app, host='0.0.0.0', port=5001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment