FastAPI之表单数据

FastAPI 表单数据处理教程

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,它用 Python 3.6+类型提示的特性旨在方便和快速地设计和构建 APIs,并且减少代码的冗余与错误。下面将介绍如何在 FastAPI 中处理表单数据。

安装 FastAPI 和 Uvicorn

首先,确保你已经安装了FastAPI和Uvicorn,它们将允许我们运行我们的Web应用。在命令行中运行以下命令来安装这些包(如果你尚未安装):

pip install fastapi
pip install uvicorn

要使用表单,需预先安装 python-multipart

pip install python-multipart

创建 FastAPI 应用

创建一个新的 Python 文件,如 main.py,并导入需要的模块:

from fastapi import FastAPI, Form
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

创建表单数据模型

虽然处理表单时通常不需要Pydantic模型,但定义它可以让我们更便捷地进行验证和文档化。

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

创建 POST 路由处理表单提交

在FastAPI中创建一个接受表单数据的路由。我们将使用Form类来定义应该从表单中接收哪些字段。

@app.post("/items/")
async def create_item(name: str = Form(...), description: str = Form(None), 
                      price: float = Form(...), tax: Optional[float] = Form(None)):
    item = {"name": name, "description": description, "price": price, "tax": tax}
    return item

在上面的例子中, ... 表明该字段是必填的,而 None 则意味着该字段是可选的。

运行应用

现在,你可以通过 Uvicorn 来运行你的应用。在命令行中运行以下命令:

uvicorn main:app --reload

--reload 参数使得在代码更新时服务器能够自动重新加载。

测试应用

打开浏览器,访问 http://127.0.0.1:8000/docs ,你将看到由 FastAPI 自动生成的交互式API文档。

在文档页面上,你能看到你创建的 /items/ 路由。你可以使用“Try it out”功能来发送一个表单数据请求,填写相应字段并执行。
在这里插入图片描述

总结

在这份教程中,我们学会了如何在 FastAPI 中通过创建简单的路由处理表单数据。你可以使用Form帮助表单验证和自动生成文档。通过结合 FastAPI 自动生成的文档,可以方便地测试和交互你的 API。

希望你能在构建自己的 FastAPI 应用时找到这份教程有用。快去试试吧!

<think>我们使用FastAPI处理表单数据时,通常需要安装`python-multipart`,因为表单数据通常以`multipart/form-data`编码。 在FastAPI中,可以使用`Form`来声明表单参数。 以下是一个简单的例子,展示如何接收表单数据: 假设我们有一个登录表单,包含用户名和密码。 步骤: 1. 导入FastAPI和Form。 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 需要额外中间件)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值