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} 注册成功!'}
相关推荐
Lucas_coding1 天前
【Claude Code Router】 Claude Code 兼容 OpenAI 格式 API, Claude code 接入本地部署模型
人工智能·python
测试员周周1 天前
【AI测试系统】第5篇:从 Archon 看 AI 工程化落地:为什么"确定性编排+AI 弹性智能"是终局?
人工智能·python·测试
大飞记Python1 天前
【2026更新】Python基础学习指南(AI版)——04数据类型
开发语言·人工智能·python
Hello eveybody1 天前
介绍一下背包DP(Python)
开发语言·python·动态规划·dp·背包dp
2301_795099741 天前
让 CSS Grid 自适应容器尺寸的动态布局方案
jvm·数据库·python
呆萌的代Ma1 天前
python读取并加载.env的配置文件
python
Muyuan19981 天前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
U盘失踪了1 天前
python curl转python脚本
开发语言·chrome·python
FQNmxDG4S1 天前
Java泛型编程:类型擦除与泛型方法的应用场景
java·开发语言·python
bzmK1DTbd1 天前
JDBC编程规范:PreparedStatement与事务管理
数据库·python·eclipse