From d6528eb80d3c7afc71d00dca4da5a13b333b001d Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Thu, 8 Sep 2022 16:15:38 +0800 Subject: Flash error message --- __main__.py | 17 ++++++++++++----- 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 @@ + {% with messages = get_flashed_messages() %} + {% if messages %} + + {% endif %} + {% endwith %}
- +
-- cgit v1.2.3