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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
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/<path:name>")
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)
|