Request Forms ve Files¶
🌐 Translation by AI and humans
This translation was made by AI guided by humans. 🤝
It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖
You can improve this translation by helping us guide the AI LLM better.
File ve Form kullanarak aynı anda hem dosyaları hem de form alanlarını tanımlayabilirsiniz.
Bilgi
Yüklenen dosyaları ve/veya form verisini almak için önce python-multipart paketini kurun.
Bir virtual environment oluşturduğunuzdan, onu aktive ettiğinizden ve ardından paketi kurduğunuzdan emin olun, örneğin:
$ pip install python-multipart
File ve Form Import Edin¶
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
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 ve Form Parametrelerini Tanımlayın¶
Dosya ve form parametrelerini, Body veya Query için yaptığınız şekilde oluşturun:
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
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,
}
Dosyalar ve form alanları form data olarak upload edilir ve siz de dosyaları ve form alanlarını alırsınız.
Ayrıca bazı dosyaları bytes olarak, bazılarını da UploadFile olarak tanımlayabilirsiniz.
Uyarı
Bir path operation içinde birden fazla File ve Form parametresi tanımlayabilirsiniz; ancak request'in body'si application/json yerine multipart/form-data ile encode edileceği için, JSON olarak almayı beklediğiniz Body alanlarını aynı anda tanımlayamazsınız.
Bu FastAPI kısıtı değildir; HTTP protokolünün bir parçasıdır.
Özet¶
Aynı request içinde hem veri hem de dosya almanız gerektiğinde File ve Form'u birlikte kullanın.