FastAPI 学习之路(十六)Form表单

FastAPI表单验证实战
本文介绍使用FastAPI实现表单验证的过程,包括登录及注册功能,并通过实例演示了如何设置表单字段的长度和正则限制。

我们首先来安装下,

pip install python-multipart

 我们去实现一个登录的表单。当密码等于buzhidao返回用户名,其他的返回失败。

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
    if password == "buzhidao":
        return {"username": username}
    return "password is wrong"

 看下调试结果

我们输入正确的用户名密码。

这样一个简单的Form表单就完成了。其实还是很简单的就是导入对应的依赖库,然后去组织对应的请求即可。那么我们再来实现一个需求。

       我们现在有一个注册的表单,我们的用户名长度为8-16位的字母,密码的长度是8-16位的数字。符合要求,我们认为注册成功,返回对应的用户名。这样的需求我们应该怎么实现。

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/register")
def register(
        
<think>我们使用FastAPI处理表单数据时,通常需要安装`python-multipart`,因为表单数据通常以`multipart/form-data`编码。 在FastAPI中,可以使用`Form`来声明表单参数。 以下是一个简单的例子,展示如何接收表单数据: 假设我们有一个登录表单,包含用户名和密码。 步骤: 1. 导入FastAPIForm。 2. 创建一个FastAPI应用实例。 3. 定义一个路径操作,使用`POST`方法。 4. 在路径操作函数中,声明表单参数,使用`Form(...)`,其中`...`表示该字段是必需的。如果要声明可选字段,可以使用`Form(None)`或设置默认值。 注意:必须安装`python-multipart`,因为FastAPI需要它来处理表单数据。 安装命令: ```bash pip install python-multipart ``` 示例代码: </think># FastAPI 表单提交实现指南 在 FastAPI 中处理表单提交需要使用 `Form` 类来声明表单字段。以下是完整的实现方案: ## 完整示例代码 ```python from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse from pydantic import BaseModel import uvicorn app = FastAPI() # 简单的 HTML 表单用于测试 html_form = """ <!DOCTYPE html> <html> <head> <title>FastAPI 表单示例</title> <style> body { font-family: Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 20px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; } button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; } </style> </head> <body> <h1>用户注册表单</h1> <form action="/submit-form" method="post"> <div class="form-group"> <label for="username">用户名:</label> <input type="text" id="username" name="username" required> </div> <div class="form-group"> <label for="email">电子邮箱:</label> <input type="email" id="email" name="email" required> </div> <div class="form-group"> <label for="password">密码:</label> <input type="password" id="password" name="password" required> </div> <div class="form-group"> <label for="bio">个人简介:</label> <textarea id="bio" name="bio" rows="4"></textarea> </div> <div class="form-group"> <label> <input type="checkbox" name="subscribe" value="true"> 订阅新闻邮件 </label> </div> <button type="submit">提交</button> </form> </body> </html> """ @app.get("/", response_class=HTMLResponse) async def show_form(): """显示表单页面""" return html_form @app.post("/submit-form") async def handle_form( username: str = Form(..., min_length=3, max_length=20, description="用户名,3-20个字符"), email: str = Form(..., regex=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", description="有效的电子邮件地址"), password: str = Form(..., min_length=8), bio: str = Form(None, max_length=200), subscribe: bool = Form(False) ): """处理表单提交""" # 在实际应用中,这里通常会进行数据库操作 # 这里简单返回提交的数据 return { "message": "表单提交成功", "username": username, "email": email, "password_length": len(password), # 安全考虑,不返回实际密码 "bio": bio, "subscribed": subscribe } # 使用 Pydantic 模型的替代方案 class UserRegistration(BaseModel): username: str email: str password: str bio: str = None subscribe: bool = False @app.post("/submit-form-model") async def handle_form_model(user: UserRegistration = Form(...)): """使用 Pydantic 模型处理表单提交""" return { "message": "使用模型处理表单成功", "user_data": user.dict(exclude={"password"}), # 排除敏感字段 "password_length": len(user.password) } if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` ## 代码解释 ### 1. 创建表单页面 - 使用 `@app.get` 路由返回 HTML 表单 - 表单使用 POST 方法提交到 `/submit-form` 端点 - 包含文本输入、邮箱、密码、文本域和复选框等多种表单元素 ### 2. 处理表单提交(基本方法) - 使用 `@app.post` 装饰器创建表单处理端点 - 使用 `Form` 类声明表单字段参数: ```python username: str = Form(..., parameters) ``` - `...` 表示必需字段 - 可添加验证参数:`min_length`, `max_length`, `regex` 等 - 支持多种数据类型:`str`, `int`, `float`, `bool` 等 - 可选字段使用 `Form(None)` ### 3. 表单数据处理 - 参数直接映射到函数参数 - 示例中返回包含提交数据的 JSON 响应 - 安全实践:不直接返回密码等敏感信息 ### 4. 使用 Pydantic 模型(高级方法) - 创建继承自 `BaseModel` 的表单模型 - 在端点参数中使用 `user: UserRegistration = Form(...)` - 优点:代码更整洁、支持复杂验证、自动生成文档 ## 运行与测试 1. 安装依赖: ```bash pip install fastapi uvicorn python-multipart ``` 2. 运行应用: ```bash python your_file.py ``` 3. 访问 `http://localhost:8000` 填写表单并提交 4. 测试端点: ```bash curl -X POST -d "username=john&email=john@example.com&password=secure123" http://localhost:8000/submit-form ``` ## 表单提交最佳实践 1. 始终验证客户端输入 2. 使用 HTTPS 保护敏感数据 3. 对密码进行哈希处理(不要存储明文) 4. 限制文本字段长度防止攻击 5. 使用 CSRF 保护(FastAPI 需要额外中间件)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值