Reputation: 1638
I have a couple of .xlsx files uploaded from a form within a Django website. For reasons that aren't worth explaining, I need to get a file path for these file objects as opposed to performing actions directly upon them. Tl;dr: I'd have to spend days re-writing a ton of someone else's code.
Is the following the best way to do this:
Thanks.
Upvotes: 1
Views: 2521
Reputation: 1138
NamedTemporaryFile. The with block does all the cleanup for you, and the Named version of this means the temp file can be handed off by filename to some other process if you have to go that far. Sorta example (note this is mostly coded on the fly so no promises of working code here)
import tempfile
def handler(inmemory_fh):
with tempfile.NamedTemporaryFile() as f_out:
f_out.write(inmemory_fh.read()) # or something
subprocess.call(['/usr/bin/dosomething', f_out.name])
When the withblock exits, the file gets removed.
As for is that the best way? Enh, you might be able to reach into their uploader code and tell django to write it to a file, or you can poke at the django settings for it (https://docs.djangoproject.com/en/1.10/ref/settings/#file-upload-settings) and see if django will just do it for you. Depends on what exactly you need to do with that file.
Upvotes: 2