Request Forms और Files¶
🌐 एआई और मनुष्यों द्वारा किया गया अनुवाद
यह अनुवाद मनुष्यों के मार्गदर्शन में एआई द्वारा किया गया है। 🤝
इसमें मूल अर्थ को गलत समझने या अप्राकृतिक लगने आदि जैसी गलतियाँ हो सकती हैं। 🤖
आप हमें एआई LLM को बेहतर मार्गदर्शन करने में मदद करके इस अनुवाद को बेहतर बना सकते हैं।
आप File और Form का उपयोग करके files और form fields को एक ही समय में define कर सकते हैं।
नोट
अपलोड की गई files और/या form data प्राप्त करने के लिए, पहले python-multipart install करें।
सुनिश्चित करें कि आप एक virtual environment बनाएँ, उसे activate करें, और फिर इसे install करें, उदाहरण के लिए:
$ pip install python-multipart
File और Form Import करें¶
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 और Form parameters define करें¶
file और form parameters उसी तरह बनाएँ जैसे आप 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
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,
}
files और form fields, form data के रूप में अपलोड किए जाएँगे और आपको files और form fields प्राप्त होंगे।
और आप कुछ files को bytes के रूप में और कुछ को UploadFile के रूप में declare कर सकते हैं।
चेतावनी
आप एक path operation में कई File और Form parameters declare कर सकते हैं, लेकिन आप साथ ही ऐसे Body fields declare नहीं कर सकते जिन्हें आप JSON के रूप में प्राप्त करने की अपेक्षा करते हैं, क्योंकि request में body application/json के बजाय multipart/form-data का उपयोग करके encoded होगी।
यह FastAPI की कोई सीमा नहीं है, यह HTTP protocol का हिस्सा है।
Recap¶
जब आपको एक ही request में data और files प्राप्त करने की आवश्यकता हो, तो File और Form को साथ में उपयोग करें।