From 60c12a00c7cecf2721ec426472fe85db02bf4f5d Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Thu, 8 Sep 2022 15:38:20 +0800 Subject: Flask server --- __main__.py | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++ templates/index.html | 17 +++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 __main__.py create mode 100644 templates/index.html diff --git a/__main__.py b/__main__.py new file mode 100644 index 0000000..d3753c5 --- /dev/null +++ b/__main__.py @@ -0,0 +1,69 @@ +from flask import Flask, render_template, request, send_file, after_this_request +import os +import logging +from tempfile import gettempdir +from pathlib import Path +from .compress import compress + +UPLOAD_FOLDER = Path(gettempdir()) / "risksheet" + +app = Flask(__name__) +app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER + +logging.basicConfig(filename=UPLOAD_FOLDER / "risksheet.log") + + +@app.get("/") +def index(): + return render_template("index.html") + + +@app.post("/") +def sheet(): + # receive and validate file + try: + file = request.files["file"] + except KeyError: + return "No file" + if not file.filename.endswith(".xlsx"): + return "Not excel file" + + # save file + fp = UPLOAD_FOLDER / file.filename.split("/")[-1] + file.save(fp) + + # compress sheet + try: + compressed_fp = compress(str(fp)) + except: + logging.exception(f"Failed to compress {fp}") + return "Error" + + # delete sheets after response + @after_this_request + def delete_sheets(resp): + for f in [fp, compressed_fp]: + try: + os.remove(f) + except FileNotFoundError: + pass + except: + logging.exception(f"Failed to delete {f}") + return resp + + # send compressed file + return send_file( + compressed_fp, + # thanks microsoft for this cursed MIME type + mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + as_attachment=True, # ask client to download file + ) + + +if __name__ == "__main__": + try: + os.mkdir(UPLOAD_FOLDER) + except FileExistsError: + pass + + app.run(port=1979) diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..1dce9c4 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,17 @@ + + + + 高中风险地区表格压缩器 + + +
+ + +
+ + -- cgit v1.2.3