from hashlib import sha256
from pathlib import Path
from uuid import uuid4
from flask import Blueprint,current_app,jsonify,redirect,render_template,request,url_for
from flask_wtf import FlaskForm
from werkzeug.utils import secure_filename
from wtforms import EmailField,StringField,SubmitField
from wtforms.validators import DataRequired,Email,Length
forms=Blueprint("forms",__name__)
class Contact(FlaskForm):
name=StringField("观测员",filters=[lambda value:(value or "").strip()],
validators=[DataRequired(),Length(min=1,max=50)])
email=EmailField("邮箱",validators=[DataRequired(),Email(check_deliverability=False)])
submit=SubmitField("提交回执")
@forms.route("/plain",methods=["GET","POST"])
def plain():
if request.method=="GET":
return render_template("plain.html")
name=request.form.get("name","").strip()
email=request.form.get("email","").strip()
if not name or not email:
return render_template("notice.html",message="两项都要填写。"),400
return render_template("receipt.html",name=name,email=email),201
@forms.route("/contact",methods=["GET","POST"])
def contact():
form=Contact()
if form.validate_on_submit():
return redirect(url_for(".sent"),code=303)
return render_template("contact.html",form=form),422 if request.method=="POST" else 200
@forms.get("/sent")
def sent():
return render_template("notice.html",message="回执已通过字段校验。")
@forms.route("/upload",methods=["GET","POST"])
def upload():
if request.method=="GET":
return render_template("upload.html")
file=request.files.get("sample")
name=secure_filename(file.filename or "") if file is not None else ""
if not name or Path(name).suffix.lower()!=".txt":
return {"error":"select a .txt fixture"},400
directory=Path(current_app.config["UPLOAD_FOLDER"])
directory.mkdir(parents=True,exist_ok=True)
target=directory/(uuid4().hex+"-"+name)
with target.open("xb") as stream:
file.save(stream)
data=target.read_bytes()
return jsonify(name=name,size=len(data),sha256=sha256(data).hexdigest()),201
本例需在 Windows、CPython 3.12、Flask 3.1.3、Flask-WTF 1.3.0、SQLAlchemy 2.1.6,隔离环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12、Flask 3.1.3、Flask-WTF 1.3.0、SQLAlchemy 2.1.6,隔离环境
入口文件:projects/flask-tidal-station/forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
forms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12、Flask 3.1.3、Flask-WTF 1.3.0、SQLAlchemy 2.1.6,隔离环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202611a482.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a491.zip