FastAPI 数据验证 Pydantic Flask 用 WTForms

使用 Flask + WTForms

python 复制代码
from flask import Flask, render_template, request
from wtforms import Form, StringField, validators

app = Flask(__name__)

# 1. 定义表单类
class RegistrationForm(Form):
    username = StringField('用户名', [
        validators.Length(min=4, max=25, message='长度需在4-25之间'),
        validators.DataRequired(message='用户名不能为空')
    ])
    email = StringField('邮箱', [
        validators.Email(message='请输入有效的邮箱地址'),
        validators.DataRequired(message='邮箱不能为空')
    ])

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm(request.form)  # 2. 手动绑定请求数据
    if request.method == 'POST' and form.validate():  # 3. 手动验证
        # 4. 验证通过,获取数据
        username = form.username.data
        email = form.email.data
        return f'用户 {username} 注册成功!'
    
    # 5. 渲染表单和错误信息
    return render_template('register.html', form=form)

使用 FastAPI + Pydantic

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, Field

app = FastAPI()

# 1. 定义数据模型
class UserRegistration(BaseModel):
    username: str = Field(..., min_length=4, max_length=25, description='用户名')
    email: EmailStr = Field(..., description='邮箱地址')

# 2. 在路径操作函数中直接声明模型类型
@app.post('/register')
async def register(user: UserRegistration):  # FastAPI 自动完成绑定、解析和验证
    # 3. 验证通过,直接使用
    return {'message': f'用户 {user.username} 注册成功!'}
相关推荐
stephon_10018 分钟前
Agent 接入 MCP 后上下文爆炸、工具选串?一种“按需激活“的工具加载方案(含实现)
人工智能·python·ai
TickDB26 分钟前
统一行情 API 查 A 股、港股、美股和数字货币:code=0 不代表 symbol 一个没少
人工智能·python·websocket·mcp·行情数据 api
大貔貅喝啤酒8 小时前
Python Requests库教程
自动化测试·python·requests库
copyer_xyf8 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf8 小时前
Prompt 组织管理
后端·python·agent
shimly1234569 小时前
python3 uvicorn 是啥?
python
CTA量化套保10 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链
GIS数据转换器10 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
贤哥哥yyds11 小时前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅11 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python