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} 注册成功!'}
相关推荐
鲨鱼辣钊4 小时前
【FastAPI筑基-Day19】APScheduler定时任务全实战|自动执行、动态启停、后台常驻
java·spring·fastapi
傲笑风10 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
维基框架10 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
谢白羽14 小时前
SGLang的AWQ量化笔记
笔记·python·sglang
迷迭香yy14 小时前
基金档案数据工程实战从收入分析到持仓穿透的Python解析 IG50免费开源股票数据API接口
开发语言·python
清水白石00815 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
️学习的小王15 小时前
Git项目提交忽略文件怎么做?以Python项目为例,详解.gitignore
git·python·elasticsearch
前端 贾公子15 小时前
第09章:上下文与记忆 (6)
开发语言·前端·python
evans在进步15 小时前
Java 常用设计模式入门:建造者、工厂、单例、外观与代理
java·python·设计模式
jayson.h16 小时前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python