summaryrefslogtreecommitdiff
path: root/__main__.py
blob: 190271840a2bed4c3ec3c39c21cfdc018bb4eac4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from flask import Flask, render_template, request, redirect, flash, send_file, after_this_request
import os
import logging
import secrets
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
# 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()

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:
        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)