Form表单数据
官方文档地址:https://fastapi.tiangolo.com/zh/tutorial/request-forms/
接收的不是 JSON,而是表单字段时,要使用 Form
要使用表单,需预先安装 python-multipart:pip install python-multipart
# 从 fastapi 导入 Form
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)): # 定义 Form 参数
return {"username": username}
OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 username 和 password。该规范要求字段必须命名为 username 和 password,并通过表单字段发送,不能用 JSON。
声明表单体要显式使用 Form ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
HTML 表单()向服务器发送数据通常使用「特殊」的编码。FastAPI 要确保从正确的位置读取数据,而不是读取 JSON。
表单数据的「媒体类型」编码一般为 application/x-www-form-urlencoded。但包含文件的表单编码为 multipart/form-data。
可在一个路径操作中声明多个 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码是
application/x-www-form-urlencoded,不是application/json。
代码示例
├── main.py
└── templates
└── index.html
└── post.html
main.py
# -*- coding: UTF-8 -*-
from fastapi import FastAPI, Form, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.post("/user/")
async def form_text(request: Request, username: str = Form(...), password: str = Form(...)):
print('username', username)
print('password', password)
# return {'text_1':text_1 , 'text_2': text_2}
return templates.TemplateResponse('index.html', {'request': request, 'username': username, 'password': password})
@app.get("/")
async def main(request: Request):
return templates.TemplateResponse('post.html', {'request': request})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
templates/index.html
Signin Template for Bootstrap
HELLO..{{ username }}
HELLO..{{ password }}
templates/post.html
Title