-
-
Notifications
You must be signed in to change notification settings - Fork 152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to create NamedTemporaryFile without the context manager? #161
Comments
Yeah, that sounds about right, but you'll need to remember to |
With the implementation as it is now,
from contextlib import asynccontextmanager
@asynccontextmanager
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)
yield temp_file # Note `yield` instead of `return` here. Please read `contextlib` docs if you don't understand what this is doing.
# Example usage
async with create_temp_file_async(orig_file, ".tmp") as temp_file:
await do_something_with_it_while_its_open(temp_file)
# This is exactly your last example from the original comment
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
# Example usage
temp_file = create_temp_file_async(file, suffix)
try:
await do_something_with_it_while_its_open(temp_file)
finally:
await temp_file.__aexit__(None, None, None) As you can see, the first approach encapsulates the interaction much better and is very Pythonic. As I said, you really shouldn't do the second one. By putting the onus on the caller, it's fragile and a terrible intermixing of concerns. @Tinche temp_file = create_temp_file_async(suffix=suffix) # Again, assuming someone, for whatever reason, wants a non-CM wrapper like option 2 above.
async with aclosing(temp_file):
await do_something_with_it_while_its_open(temp_file) |
I have a helper function which creates a temporary file and returns it. That's how it is done synchronously:
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 thewith
block: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:Is this the right approach or is there some better way to do it?
The text was updated successfully, but these errors were encountered: