Skip to content
Advertisement

How to save UploadFile in FastAPI

I accept the file via POST. When I save it locally, I can read the content using file.read (), but the name via file.name incorrect(16) is displayed. When I try to find it by this name, I get an error. What might be the problem?

My code:

JavaScript

Advertisement

Answer

Background

UploadFile is just a wrapper around SpooledTemporaryFile, which can be accessed as UploadFile.file.

SpooledTemporaryFile() […] function operates exactly as TemporaryFile() does

And documentation about TemporaryFile says:

Return a file-like object that can be used as a temporary storage area. [..] It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

async def endpoint

You should use the following async methods of UploadFile: write, read, seek and close. They are executed in a thread pool and awaited asynchronously.

For async writing files to disk you can use aiofiles. Example:

JavaScript

Or in the chunked manner, so as not to load the entire file into memory:

JavaScript

def endpoint

Also, I would like to cite several useful utility functions from this topic (all credits @dmontagu) using shutil.copyfileobj with internal UploadFile.file. This functions can be invoked from def endpoints:

JavaScript

Note: you’d want to use the above functions inside of def endpoints, not async def, since they make use of blocking APIs.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement