Creating file from Django <InMemoryUploadedFile>
<p>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. </p>

<p>Is the following the best way to do this: </p>

<ol>
<li>Save objects as files</li>
<li>Get filepaths of newly created files</li>
<li>do_something()</li>
<li>Delete files</li>
</ol>

<p>Thanks.</p>

<p>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)</p>

<pre><code>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])
</code></pre>

<p>When the withblock exits, the file gets removed.</p>

<p>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 (<a href="https://docs.djangoproject.com/en/1.10/ref/settings/#file-upload-settings" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/settings/#file-upload-settings</a>) and see if django will just do it for you. Depends on what exactly you need to do with that file.</p>

python django python-2.7