Bastien D
Bastien D

Reputation: 1465

Upload small file to FastAPI enpoint but UploadFile content is empty

I am trying to upload file (csv) to FastAPI POST endpoint.

This is the server code:

@app.post("/csv/file/preview")
async def post_csv_file_preview(file: UploadFile):
    """

    :param file:
    :return:
    """
    contents = file.file.read()
    print(contents)

But contents is empty if the file is small. If I increase the file content (add new lines in the csv file), without any others changes, it is working.

If I directly get the request body, the file content is returned normally.

print(await request.body())

The problem is only with my production server, not localally:

PYTHONPATH=/var/www/api/current /var/www/api/current/venv/bin/python /var/www/api/current/venv/bin/uvicorn main:app --reload --port=8004

I dont understand

Upvotes: 3

Views: 2135

Answers (1)

Bastien D
Bastien D

Reputation: 1465

Thanks to the comment from Chris, I solved my problem by adding the .seek() method before reading the file contents.

@app.post("/csv/file/preview")
def post_csv_file_preview(file: UploadFile):
    """

    :param file:
    :return:
    """
    file.file.seek(0)
    contents = file.file.read()
    print(contents)

Upvotes: 3

Related Questions