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} 注册成功!'}
相关推荐
weixin_156241575761 天前
基于YOLOv8深度学习花卉识别系统摄像头实时图片文件夹多图片等另有其他的识别系统可二开
大数据·人工智能·python·深度学习·yolo
AI_Claude_code1 天前
ZLibrary访问困境方案三:Web代理与轻量级转发服务的搭建与优化
爬虫·python·web安全·搜索引擎·网络安全·web3·httpx
小陈工1 天前
2026年4月7日技术资讯洞察:下一代数据库融合、AI基础设施竞赛与异步编程实战
开发语言·前端·数据库·人工智能·python
时空无限1 天前
ansible 由于不同主机 python 版本不同执行报错
python·ansible
ZhengEnCi1 天前
P2E-Python字典操作完全指南-从增删改查到遍历嵌套的Python编程利器
python
alanesnape1 天前
使用AVL平衡树和列表实现 map容器 -- 附加测试/python代码
python·map·avl 平衡树·bst树·二叉树旋转
许杰小刀1 天前
FastAPI + Vue 前后端分离实战:我的项目结构“避坑指南”
前端·vue.js·fastapi
卤炖阑尾炎1 天前
Python 网络编程实战:从 TCP/UDP 基础到高并发服务器开发
网络·python·tcp/ip
weixin_513449961 天前
walk_these_ways项目学习记录第八篇(通过行为多样性 (MoB) 实现地形泛化)--策略网络
开发语言·人工智能·python·学习
飞Link1 天前
逆向兼容的桥梁:3to2 自动化降级工具实现全解析
运维·开发语言·python·自动化