diff options
author | Frederick Yin <fkfd@fkfd.me> | 2022-09-08 15:38:20 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2022-09-08 15:38:20 +0800 |
commit | 60c12a00c7cecf2721ec426472fe85db02bf4f5d (patch) | |
tree | 69e9914a08204a0a07154485486ff845945576dc | |
parent | 010d65d7188fb806733d7fe7deb6c3e3117b4537 (diff) |
Flask server
-rw-r--r-- | __main__.py | 69 | ||||
-rw-r--r-- | templates/index.html | 17 |
2 files changed, 86 insertions, 0 deletions
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 @@ +<!DOCTYPE html> +<html> + <head> + <title>高中风险地区表格压缩器</title> + <link rel="stylesheet" href="/static/index.css" + </head> + <body> + <form method="post" action="/" enctype="multipart/form-data"> + <input + name="file" + type="file" + accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + /> + <input type="submit" /> + </form> + </body> +</html> |