[Python] How to Upload File using FastAPI?

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

  1. Stack

    Stack Membro Participativo

    I am using FastAPI to upload a file according to the official documentation, as shown below:

    @app.post("/create_file")
    async def create_file(file: UploadFile = File(...)):
    file2store = await file.read()
    # some code to store the BytesIO(file2store) to the other database


    When I send a request using Python requests library, as shown below:

    f = open(".../file.txt", 'rb')
    files = {"file": (f.name, f, "multipart/form-data")}
    requests.post(url="SERVER_URL/create_file", files=files)


    the file2store variable is always empty. Sometimes (rarely seen), it can get the file bytes, but almost all the time it is empty, so I can't restore the file on the other database.

    I also tried the bytes rather than UploadFile, but I get the same results. Is there something wrong with my code, or is the way I use FastAPI to upload a file wrong?

    Continue reading...

Compartilhe esta Página