表单
如果要获取表单的数据,需要进行一下步骤:
- 导入 fastapi 中的 Form
- 在模板中通过 Form(...) 来获取参数的值
假设我们做了一个登录页面,有两个field,一个叫做 username ,一个叫做 password,那么获取参数的方式如下:
from starlette.requests import Request
from fastapi import FastAPI, Form
from starlette.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 templates.TemplateResponse('index.html', {'request': request, 'username': username, 'password': password})
其中(...)表示这是必须的参数。
上传文件
上传文件时,表单的 method 必须是 "post" ,enctype 要是 "multipart/form-data" 。同时,还必须安装 python-multipart 包,否则会报 400 bad request 错误。
from starlette.requests import Request
from fastapi import FastAPI, File, UploadFile
from starlette.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.post('/single_file')
async def single_file(request: Request,
file: UploadFile = File(...)):
res = await file.read()
with open(file.filename, "wb") as f:
f.write(res)
return {"message": "success", 'filename': file.filename}
@app.get('/')
async def upload(request: Request):
return templates.TemplateResponse('index.html', {"request": request})
请求体(Request Body)
Request body 即通过 post 请求的请求体传来的数据,而不是明文写入 url 链接的参数。请求体的数据通常是通过 JSON 传入的,例如:
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
我们可以利用 http://localhost:8000/docs 文档功能传入 JSON 数据进行测试,也可以使用 curl 命令进行测试。请求体可以和路径参数及查询参数合并使用。
网友评论