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} 注册成功!'}
相关推荐
第一程序员11 分钟前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk816326 分钟前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
weixin_BYSJ198740 分钟前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
EQUINOX12 小时前
【论文阅读】| MoCo精读
论文阅读·人工智能·python·深度学习·机器学习
用户8356290780513 小时前
使用 Python 自动化 Excel 公式和函数:完整指南
后端·python
敲代码的嘎仔3 小时前
实习日志day6--实习日志day6--title命名规范化&businessType纠正&补充缺失的@Log注解&报警与通信模块补充&产出阶段总结文档
java·开发语言·人工智能·git·python·实习·大二
江华森3 小时前
Python 实现高德地图找房(一):环境搭建与数据爬虫
开发语言·爬虫·python
VIP_CQCRE4 小时前
用 Ace Data Cloud 快速接入 OpenAI Chat Completions:对话、流式、多轮和多模态一篇打通
python·ai·openai·api·教程
AOwhisky4 小时前
Python 学习笔记(第三期)——流程控制:条件判断与循环结构
运维·笔记·python·学习·云原生·流程控制·循环
老迟到的茉莉5 小时前
Hermes 是谁?跟 Claude Code 差在哪
开发语言·python