from flask import ( Flask, render_template, request, redirect, flash, send_file, after_this_request, send_from_directory, ) import os import logging import secrets from tempfile import gettempdir from pathlib import Path from .compress import compress UPLOAD_FOLDER = Path(gettempdir()) / "risksheet" URL_PATH = "/xlsx" # https://example.com/xlsx app = Flask(__name__) app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER # NOTE: the secret key will be regenerated each time this application is run # this is ok because we don't store credentials in the cookie app.secret_key = secrets.token_hex() app.static_url_path = "xlsx/static" logging.basicConfig(filename=UPLOAD_FOLDER / "risksheet.log", level=logging.WARNING) @app.get(URL_PATH + "/static/") def subpath_static(name): return send_from_directory("static", name) @app.get(URL_PATH) def index(): return render_template("index.html", path=URL_PATH) @app.post(URL_PATH) def sheet(): # receive and validate file try: file = request.files["file"] except KeyError: flash("没有上传文件") return redirect("/") if not file.filename.endswith(".xlsx"): flash("文件不是 Excel (.xlsx)") return redirect("/") # 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}") flash("压缩文件时出现错误,请检查格式是否正确") return redirect("/") # delete sheets after response (only if it is successful) @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)