How to access a tempfile object across 2 separate requests (was:views) in Django

710 views Asked by At

Can't find a direct, head on answer to this. Is there a way to access a tempfile in Django across 2 distinct views? Say I have the following code:

view#1(request):
   temp = tempfile.NamedTemporaryFile()
   write_book.save(temp_file)
   temp_file_name = temp_file.name
   print temp_file_name
   request.session['output_file_name'] = temp_file_name
   request.session.modified = True
   return #something or other

view#2(request):
   temp_file_name = request.session['output_file_name']
   temp_file = open(str(temp_file_name))
   #do something with 'temp_file' here

My problem comes in specifically on view#2, the 2nd line "open(temp_file_name)". Django complains this file/pathway doesn't exist, which is consistent of my understanding of the tempfile module (that the file is 'hidden' and only available to Django).

Is there a way for me to access this file? In case it matters, I ONLY need to read from it (technically serve it for download).

2

There are 2 answers

0
user3398838 On BEST ANSWER

Thanks seddonym for attempting to answer. My partner clarified this for me...seddonym is correct for the Django version of NamedTemporaryFile. By calling the python version (sorry, don't have enough cred to post hyperlinks. Stupid rule) you CAN access across requests.

The trick is setting the delete=False parameter, and closing the file before 'returning' at the end of the request. Then, in the subsequent request, just open(file_name). Psuedo code below:

>>> import tempfile
>>> file = tempfile.NamedTemporaryFile(delete=False)
>>> file.name
'c:\\users\\(blah)\(blah)\(blah)\\temp\\tmp9drcz9'
>>> file.close()
>>> file
<closed file '<fdopen>', mode 'w+b' at 0x00EF5390>
>>> f = open(file.name)
>>> f
<open file 'c:\users\ymalik\appdata\local\temp\tmp9drcz9', mode 'r' at 0x0278C128>

This is, of course, done in the console, but it works in django as well.

3
seddonym On

I'd think of this as how to access a NamedTemporaryFile across different requests, rather than different views. Looking at this documentation on NamedTemporaryFile, it says that the file can be opened across the same process, but not necessarily across multiple processes. Perhaps your other view is being called in a different Django process.

My suggestion would be to abandon the use of NamedTemporaryFile and instead just write it as a permanent file, then delete the file in the other view.