[Python] FastAPI - upload files with other models fields [duplicate]

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I have a small project in FastApi and I want to upload a file along with the model. I have the following model (standard order):

    class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    is_shipped = Column(Boolean)
    filename = Column(String)


    and basic pydantic schemas (for data validation):

    from pydantic import BaseModel

    class OrderBase(BaseModel):
    name: str


    class OrderCreate(OrderBase):
    filename: str


    class Order(OrderBase):
    id: int
    is_shipped: bool

    class Config:
    orm_mode = True


    I also have two main routers, one for file uploads and one for order uploads. (Ideally I would like to keep two routers because it gives me more flexibility)

    file_list = {}

    @app.post("/upload-files/")
    async def upload_files(files: List[UploadFile] = File(...)):
    file_ids = []
    for file in files:
    file_id = str(uuid4())
    file_ids.append(file_id)

    file_list[file_id] = file.filename
    return {"file_ids" : file_ids}

    @app.post("/submit-form/")
    async def submit_form(data: str = Form(...), file_ids: List[str] = Form(...)):
    return {"data" : data, "file_references" : [file_list[file_id] for file_id in file_ids if file_id in file_list]}


    The main difficulty is that in order to load an order from attachments I must first contact one routers and then another. I would like to be able to do it all at once. How to achieve this?

    What would a form look like where I could upload a model and a file at once?

    I am trying to make that when loading sqlalchemy model the attachment file is loaded at the same time.

    Continue reading...

Compartilhe esta Página