Rumah >pembangunan bahagian belakang >Tutorial Python >Bagaimana Mengendalikan Muat Naik Fail dan Data JSON Secara Serentak dalam Permintaan FastAPI POST?
from fastapi import FastAPI, UploadFile, File, Form app = FastAPI() @app.post("/data") async def data(dataConfiguration: DataConfiguration, csvFile: UploadFile = File(...)): pass
from fastapi import Form, File, UploadFile, FastAPI, Depends from typing import List, Optional from fastapi.responses import HTMLResponse from pydantic import BaseModel from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") class Base(BaseModel): name: str point: Optional[float] = None is_accepted: Optional[bool] = False def checker(data: str = Form(...)): try: return Base.model_validate_json(data) except ValidationError as e: raise HTTPException( detail=jsonable_encoder(e.errors()), status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, ) @app.post("/submit") def submit(base: Base = Depends(checker), files: List[UploadFile] = File(...)): return {"JSON Payload": base, "Filenames": [file.filename for file in files]}
from fastapi import FastAPI, status, Form, UploadFile, File, Depends, Request from pydantic import BaseModel, ValidationError from fastapi.exceptions import HTTPException from fastapi.encoders import jsonable_encoder from typing import Optional, List from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse app = FastAPI() templates = Jinja2Templates(directory="templates") class Base(BaseModel): name: str point: Optional[float] = None is_accepted: Optional[bool] = False def checker(data: str = Form(...)): try: return Base.model_validate_json(data) except ValidationError as e: raise HTTPException( detail=jsonable_encoder(e.errors()), status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, ) @app.post("/submit") def submit(base: Base = Depends(checker), files: List[UploadFile] = File(...)): return {"JSON Payload": base, "Filenames": [file.filename for file in files]}
Atas ialah kandungan terperinci Bagaimana Mengendalikan Muat Naik Fail dan Data JSON Secara Serentak dalam Permintaan FastAPI POST?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!