Skip to content

How to create NamedTemporaryFile without the context manager? #161

@mateokurti

Description

@mateokurti

I have a helper function which creates a temporary file and returns it. That's how it is done synchronously:

def create_temp_file(file, suffix):
    temp_file = NamedTemporaryFile(suffix=suffix)
    temp_file.write(file.read())
    temp_file.seek(0)
    return temp_file

Now, I wanted to make it async and started using aiofiles.tempfile.NamedTemporaryFile instead. If I use the context manager as in the following snippet, the file can't be accessed as it is deleted after the with block:

async def create_temp_file_async(file, suffix):
    async with NamedTemporaryFileAsync(suffix=suffix) as temp_file:
        await temp_file.write(file.read())
        await temp_file.seek(0)
        return temp_file

If I try it with delete=False, it works, but the file is not deleted. Based on this comment, I managed to achieve the same result, but I'm not sure if this is the only and best way to do that:

async def create_temp_file_async(file, suffix):
    temp_file = await NamedTemporaryFileAsync(suffix=suffix).__aenter__()
    await temp_file.write(file.read())
    await temp_file.seek(0)
    return temp_file

Is this the right approach or is there some better way to do it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions