On 21-07-14 17:09, alghafli wrote:
> I want to dynamically create a temporary odt file and upload it to the
> client. The file is dynamically created based on GET request parameters.
> It basically searches the database and fills the odt file with
> information. This file is temporary and should be deleted after the
> upload finishes.
tempfile.TemporaryFile is what you seem to want. The file object is
deleted automatically.
fd = tempfile.TemporaryFile()
fd.write(odt_data)
fd.seek(0)
return HttpResponse(
fd.read(),
content_type='application/vnd.oasis.opendocument.text'
)
But then you might as well skip the tempfile feature, and stream
directly from memory:
return HttpResponse(
odt_data,
content_type='application/vnd.oasis.opendocument.text'
)
> Here is how I am planning to do it. The view function creates the file
> and fills it with information. The file is created in a directory which
> is added to the STATICFILES_DIRS. The view then redirects to the file
> url and the client downloads the file.
Since your odt data is for one-time-only usage, you don't need to put
them in any kind of STATIC_FILES directory. That feature is of use to
offload download performance to the web-server, but for one-time-only
downloads there is no point.
> To delete the files, I am planning to create a class that handles
> temporary file creation and deletion. The class forces an upper limit to
> temporary files number, say 10. Any file created after 10 files will
> make the class delete older files based on modification time. I might as
> well create a thread that would delete files regularly but it would be a
> bit more complicated and unnecessary for this specific project.
Done already by the tempfile.TemporaryFile class, and totally redundant
when streaming from memory.
--
________________________________________________________________
Paul J Stevens pjstevns @ gmail, twitter, github, linkedin
www.nfg.nl/in...@nfg.nl/+31.85.877.99.97