获取表单数据
@app.post("/form") async def get_form(*, username: str = Form(...), oassword: str = Form(...), request: Request): res = { # 获取表单数据 "form": await request.form() } return res
请求结果
{
"form": {
"username": "name",
"oassword": "***"
}
}
获取 Request Body
class Item(BaseModel): id: str title: str @app.post("/body") async def get_body(item: Item, request: Request): res = { # 获取 Request Body "body": await request.json(), "body_bytes": await request.body() } return res
请求结果
{ "body": { "id": "string", "title": "string" }, "body_bytes": "{\n \"id\": \"string\",\n \"title\": \"string\"\n}" }
.body() 返回值类型是 bytes
获取 Request 存储的附加信息
async def dep_state(request: Request): # 给 request 存储附加数据 request.state.db = "Mysql+pymysql//username" @app.post("/state/", dependencies=[Depends(dep_state)]) async def get_state(request: Request): res = { "state": request.state, "db": request.state.db } return res
请求结果
{ "state": { "_state": { "db": "Mysql+pymysql//username" } }, "db": "Mysql+pymysql//username" }
获取文件上传信息
from fastapi import UploadFile, File, Form @app.post("/file") async def get_file(*, file: UploadFile = File(...), name: str = Form(...), request: Request): form_data = await request.form() res = { # 表单数据 "form": form_data, # 文件对象 UploadFile "file": form_data.get("file"), # 文件名 "filename": form_data.get("file").filename, # 文件类型 "content_type": form_data.get("file").content_type, # 文件内容 "file_content": await form_data.get("file").read() } return res
请求结果
{ "form": { "file": { "filename": "test.txt", "content_type": "text/plain", "file": {} }, "name": "表单name!!" }, "file": { "filename": "test.txt", "content_type": "text/plain", "file": {} }, "filename": "test.txt", "content_type": "text/plain", "file_content": "hello world" }
UploadFile 对象
- form_data.get("file") 返回的是一个 starlette.datastructures.UploadFile 对象
- filename、content_type 是对象实例属性
- .read() 是实例方法,读取文件
UploadFile 的其他异步方法
和 Python 普通的文件对象方法一样,只不过都是 async 异步的
- write
- read
- seek
- close