refactor: remove duplicated route and UI code
This commit is contained in:
+73
-51
@@ -31,6 +31,21 @@ REGISTRATION_SETTING_KEY = "allow_registration"
|
||||
RECORDS_PER_PAGE = 10
|
||||
|
||||
|
||||
def render_auth_template(mode: str, status_code: int = 200, captcha: str = ""):
|
||||
return render_template("login.html", mode=mode, captcha=captcha), status_code
|
||||
|
||||
|
||||
def render_login_error(message: str, status_code: int = 400):
|
||||
flash(message, "error")
|
||||
session["captcha"] = new_captcha()
|
||||
return render_auth_template("login", status_code, session["captcha"])
|
||||
|
||||
|
||||
def require_admin() -> None:
|
||||
if not current_user.is_admin:
|
||||
abort(403)
|
||||
|
||||
|
||||
def registration_allowed() -> bool:
|
||||
return AppSetting.get_bool(
|
||||
REGISTRATION_SETTING_KEY,
|
||||
@@ -45,6 +60,37 @@ def requested_page() -> int:
|
||||
return 1
|
||||
|
||||
|
||||
def paginated_uploads(query, endpoint: str):
|
||||
page = requested_page()
|
||||
pagination = (
|
||||
query.order_by(UploadRecord.upload_time.desc())
|
||||
.paginate(page=page, per_page=RECORDS_PER_PAGE, error_out=False)
|
||||
)
|
||||
if pagination.pages and page > pagination.pages:
|
||||
return pagination, redirect(url_for(endpoint, page=pagination.pages))
|
||||
return pagination, None
|
||||
|
||||
|
||||
def prediction_result_payload(artifacts, record: UploadRecord) -> dict:
|
||||
image_url = url_for("static", filename=f"images/{artifacts.image_filename}")
|
||||
importance_url = (
|
||||
url_for("static", filename=f"images/{artifacts.importance_filename}")
|
||||
if artifacts.importance_filename
|
||||
else None
|
||||
)
|
||||
return {
|
||||
"original_filename": artifacts.original_filename,
|
||||
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"image_url": image_url,
|
||||
"importance_url": importance_url,
|
||||
"excel_url": url_for("main.download_file", record_id=record.id, file_type="prediction"),
|
||||
"result_url": url_for("main.result_page"),
|
||||
"sample_count": int(artifacts.sample_count),
|
||||
"summary_rows": artifacts.summary_rows[:6],
|
||||
"analysis_text": artifacts.analysis_text,
|
||||
}
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
if current_user.is_authenticated:
|
||||
@@ -59,22 +105,18 @@ def login():
|
||||
|
||||
if request.method == "GET":
|
||||
session["captcha"] = new_captcha()
|
||||
return render_template("login.html", mode="login", captcha=session["captcha"])
|
||||
return render_auth_template("login", captcha=session["captcha"])
|
||||
|
||||
username = request.form.get("username", "").strip()
|
||||
password = request.form.get("password", "")
|
||||
captcha_input = request.form.get("captcha", "").strip().upper()
|
||||
|
||||
if captcha_input != session.get("captcha", ""):
|
||||
flash("验证码错误", "error")
|
||||
session["captcha"] = new_captcha()
|
||||
return render_template("login.html", mode="login", captcha=session["captcha"]), 400
|
||||
return render_login_error("验证码错误")
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if not user or not user.check_password(password):
|
||||
flash("用户名或密码错误", "error")
|
||||
session["captcha"] = new_captcha()
|
||||
return render_template("login.html", mode="login", captcha=session["captcha"]), 400
|
||||
return render_login_error("用户名或密码错误")
|
||||
|
||||
login_user(user, remember=bool(request.form.get("remember")))
|
||||
return redirect(url_for("main.home"))
|
||||
@@ -83,24 +125,24 @@ def login():
|
||||
@bp.route("/register", methods=["GET", "POST"])
|
||||
def register():
|
||||
if request.method == "GET":
|
||||
return render_template("login.html", mode="register", captcha="")
|
||||
return render_auth_template("register")
|
||||
|
||||
if not registration_allowed():
|
||||
flash("当前未开放自助注册,请联系管理员。", "error")
|
||||
return render_template("login.html", mode="register", captcha=""), 403
|
||||
return render_auth_template("register", 403)
|
||||
|
||||
username = request.form.get("username", "").strip()
|
||||
password = request.form.get("password", "")
|
||||
|
||||
if not username:
|
||||
flash("用户名不能为空", "error")
|
||||
return render_template("login.html", mode="register", captcha=""), 400
|
||||
return render_auth_template("register", 400)
|
||||
if len(password) < 6:
|
||||
flash("密码至少需要 6 位", "error")
|
||||
return render_template("login.html", mode="register", captcha=""), 400
|
||||
return render_auth_template("register", 400)
|
||||
if User.query.filter_by(username=username).first():
|
||||
flash("用户名已存在", "error")
|
||||
return render_template("login.html", mode="register", captcha=""), 400
|
||||
return render_auth_template("register", 400)
|
||||
|
||||
user = User(username=username, is_admin=False)
|
||||
user.set_password(password)
|
||||
@@ -108,7 +150,7 @@ def register():
|
||||
db.session.commit()
|
||||
flash("注册成功,请登录", "info")
|
||||
session["captcha"] = new_captcha()
|
||||
return render_template("login.html", mode="login", captcha=session["captcha"])
|
||||
return render_auth_template("login", captcha=session["captcha"])
|
||||
|
||||
|
||||
@bp.route("/logout", methods=["POST"])
|
||||
@@ -127,14 +169,12 @@ def home():
|
||||
@bp.route("/history")
|
||||
@login_required
|
||||
def history_page():
|
||||
page = requested_page()
|
||||
pagination = (
|
||||
UploadRecord.query.filter_by(user_id=current_user.id)
|
||||
.order_by(UploadRecord.upload_time.desc())
|
||||
.paginate(page=page, per_page=RECORDS_PER_PAGE, error_out=False)
|
||||
pagination, page_redirect = paginated_uploads(
|
||||
UploadRecord.query.filter_by(user_id=current_user.id),
|
||||
"main.history_page",
|
||||
)
|
||||
if pagination.pages and page > pagination.pages:
|
||||
return redirect(url_for("main.history_page", page=pagination.pages))
|
||||
if page_redirect:
|
||||
return page_redirect
|
||||
return render_template(
|
||||
"history.html",
|
||||
pagination=pagination,
|
||||
@@ -145,16 +185,13 @@ def history_page():
|
||||
@bp.route("/admin")
|
||||
@login_required
|
||||
def admin_dashboard():
|
||||
if not current_user.is_admin:
|
||||
abort(403)
|
||||
page = requested_page()
|
||||
pagination = (
|
||||
UploadRecord.query.options(joinedload(UploadRecord.user))
|
||||
.order_by(UploadRecord.upload_time.desc())
|
||||
.paginate(page=page, per_page=RECORDS_PER_PAGE, error_out=False)
|
||||
require_admin()
|
||||
pagination, page_redirect = paginated_uploads(
|
||||
UploadRecord.query.options(joinedload(UploadRecord.user)),
|
||||
"main.admin_dashboard",
|
||||
)
|
||||
if pagination.pages and page > pagination.pages:
|
||||
return redirect(url_for("main.admin_dashboard", page=pagination.pages))
|
||||
if page_redirect:
|
||||
return page_redirect
|
||||
return render_template(
|
||||
"admin.html",
|
||||
pagination=pagination,
|
||||
@@ -166,8 +203,7 @@ def admin_dashboard():
|
||||
@bp.route("/admin/registration", methods=["POST"])
|
||||
@login_required
|
||||
def update_registration_setting():
|
||||
if not current_user.is_admin:
|
||||
abort(403)
|
||||
require_admin()
|
||||
|
||||
allow_registration = request.form.get("allow_registration") == "on"
|
||||
AppSetting.set_bool(REGISTRATION_SETTING_KEY, allow_registration)
|
||||
@@ -195,11 +231,11 @@ def download_file(record_id: int, file_type: str):
|
||||
abort(404)
|
||||
if not (current_user.is_admin or current_user.id == record.user_id):
|
||||
abort(403)
|
||||
if file_type == "original":
|
||||
file_path = record.saved_path
|
||||
elif file_type == "prediction":
|
||||
file_path = record.prediction_path
|
||||
else:
|
||||
file_path = {
|
||||
"original": record.saved_path,
|
||||
"prediction": record.prediction_path,
|
||||
}.get(file_type)
|
||||
if file_path is None:
|
||||
abort(404)
|
||||
if not os.path.exists(file_path):
|
||||
abort(404)
|
||||
@@ -267,21 +303,7 @@ def predict():
|
||||
db.session.add(record)
|
||||
db.session.commit()
|
||||
|
||||
last_result = {
|
||||
"original_filename": artifacts.original_filename,
|
||||
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"image_url": url_for("static", filename=f"images/{artifacts.image_filename}"),
|
||||
"importance_url": (
|
||||
url_for("static", filename=f"images/{artifacts.importance_filename}")
|
||||
if artifacts.importance_filename
|
||||
else None
|
||||
),
|
||||
"excel_url": url_for("main.download_file", record_id=record.id, file_type="prediction"),
|
||||
"result_url": url_for("main.result_page"),
|
||||
"sample_count": int(artifacts.sample_count),
|
||||
"summary_rows": artifacts.summary_rows[:6],
|
||||
"analysis_text": artifacts.analysis_text,
|
||||
}
|
||||
last_result = prediction_result_payload(artifacts, record)
|
||||
session["last_result"] = last_result
|
||||
|
||||
return jsonify(
|
||||
|
||||
Reference in New Issue
Block a user