Файлы и формы в запросе¶
Вы можете определять файлы и поля формы одновременно, используя 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 вместе, когда необходимо получить данные и файлы в одном запросе.