Запити з формами та файлами¶
У FastAPI Ви можете одночасно отримувати файли та поля форми, використовуючи File і Form.
Інформація
Щоб отримувати завантажені файли та/або дані форми, спочатку встановіть python-multipart.
Переконайтеся, що Ви створили віртуальне середовище, активували його, а потім встановили бібліотеку, наприклад:
$ pip install python-multipart
Імпорт File та Form¶
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
🤓 Other versions and variants
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
Tip
Prefer to use the Annotated version if possible.
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
Оголошення параметрів File та Form¶
Створіть параметри файлів та форми так само як і для Body або Query:
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
🤓 Other versions and variants
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
Tip
Prefer to use the Annotated version if possible.
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
Файли та поля форми будуть завантажені як формові дані, і Ви отримаєте як файли, так і введені користувачем поля.
Ви також можете оголосити деякі файли як bytes, а деякі як UploadFile.
Увага
Ви можете оголосити кілька параметрів File і Form в операції шляху, але не можете одночасно оголошувати Body-поля, які очікуєте отримати у форматі JSON, оскільки запит матиме тіло, закодоване за допомогою multipart/form-data, а не application/json.
Це не обмеження FastAPI, а частина протоколу HTTP.
Підсумок¶
Використовуйте File та Form разом, коли вам потрібно отримувати дані форми та файли в одному запиті.