一、Cookie
参数
from typing import Annotated, Union
from fastapi import Cookie, FastAPI
app = FastAPI()
# 传递 cookie 参数
@app.get("/")
def root(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
二、 Header
参数
from typing import Annotated, Union
from fastapi import FastAPI, Header
app = FastAPI()
# 传递 header 参数
@app.get("/")
def root(ads_id: Annotated[Union[str, None], Header()] = None):
return {"ads_id": ads_id}
三、接收表单数据请求
基础语法:
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
def login(username: str = Form(), password: str = Form()):
return True
四、请求文件
1、基础语法:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
# 适用于小型二进制文件或数据, 会将文件存储到内存
@app.post("/files/")
def create_file(file: bytes = File()):
return {"file_size": len(file)}
# 适用于大型文件, 存储在内存的文件超出最大上限时,FastAPI 会把文件存入磁盘
@app.post("/uploadfile/")
def create_upload_file(file: UploadFile):
return {"filename": file.filename}
UploadFile
属性:
filename
::文件名
-content_type
:文件格式(MIME
类型 / 媒体类型)字符串(str
),例如,image/jpeg
file
:文件对象
UploadFile
文件支持的async
方法:
write(data)
read(size)
seek(offset)
- 例如,
await myfile.seek(0)
移动到文件开头- 执行
await myfile.read()
后,需再次读取已读取内容时,这种方法特别好用close()
因为上述方法都是
async
方法,要搭配await
使用,例如:在async
方法内,要以如下方式读取文件:
contents = await myfile.read()
在普通
def
路径操作函数 内,则可以直接访问UploadFile.file
2、可选文件上传
写法:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes | None = File(default=None)):
if not file:
return {"message": "No file sent"}
else:
return {"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile | None = None):
if not file:
return {"message": "No upload file sent"}
else:
return {"filename": file.filename}
3、多文件上传
语法:
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.post("/files/")
async def create_files(files: list[bytes] = File()):
return {"file_sizes": [len(file) for file in files]}
@app.post("/uploadfiles/")
async def create_upload_files(files: list[UploadFile]):
return {"filenames": [file.filename for file in files]}
@app.get("/")
async def main():
content = """
<body>
<form action="/files/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
</body>
"""
return HTMLResponse(content=content)