diff options
author | Frederick Yin <fkfd@fkfd.me> | 2022-09-08 16:15:38 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2022-09-08 16:15:38 +0800 |
commit | d6528eb80d3c7afc71d00dca4da5a13b333b001d (patch) | |
tree | ed3495058ddcd668c7604e44eaae12c4358f39e2 | |
parent | abef59448bf538d4ee3a3705a2563688283fcd94 (diff) |
Flash error message
-rw-r--r-- | __main__.py | 17 | ||||
-rw-r--r-- | templates/index.html | 11 |
2 files changed, 22 insertions, 6 deletions
diff --git a/__main__.py b/__main__.py index d3753c5..1902718 100644 --- a/__main__.py +++ b/__main__.py @@ -1,6 +1,7 @@ -from flask import Flask, render_template, request, send_file, after_this_request +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 @@ -9,6 +10,9 @@ 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") @@ -24,9 +28,11 @@ def sheet(): try: file = request.files["file"] except KeyError: - return "No file" + flash("没有上传文件") + return redirect("/") if not file.filename.endswith(".xlsx"): - return "Not excel file" + flash("文件不是 Excel (.xlsx)") + return redirect("/") # save file fp = UPLOAD_FOLDER / file.filename.split("/")[-1] @@ -37,9 +43,10 @@ def sheet(): compressed_fp = compress(str(fp)) except: logging.exception(f"Failed to compress {fp}") - return "Error" + flash("压缩文件时出现错误,请检查格式是否正确") + return redirect("/") - # delete sheets after response + # delete sheets after response (only if it is successful) @after_this_request def delete_sheets(resp): for f in [fp, compressed_fp]: diff --git a/templates/index.html b/templates/index.html index 1dce9c4..0576890 100644 --- a/templates/index.html +++ b/templates/index.html @@ -5,13 +5,22 @@ <link rel="stylesheet" href="/static/index.css" </head> <body> + {% with messages = get_flashed_messages() %} + {% if messages %} + <ul class="error"> + {% for message in messages %} + <li>{{ message }}</li> + {% endfor %} + </ul> + {% endif %} + {% endwith %} <form method="post" action="/" enctype="multipart/form-data"> <input name="file" type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /> - <input type="submit" /> + <input value="上传" type="submit" /> </form> </body> </html> |