Removing tmp file after return HttpResponse in django

django return file
django create temporary file for download
django filewrapper
django temporary file
django namedtemporaryfile
python tempfile
django download file

I'm using the following django/python code to stream a file to the browser:

wrapper = FileWrapper(file(path))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(path)
return response

Is there a way to delete the file after the reponse is returned? Using a callback function or something? I could just make a cron to delete all tmp files, but it would be neater if I could stream files and delete them as well from the same request.

You can use a NamedTemporaryFile:

from django.core.files.temp import NamedTemporaryFile
def send_file(request):
    newfile = NamedTemporaryFile(suffix='.txt')
    # save your data to
    wrapper = FileWrapper(newfile)
    response = HttpResponse(wrapper, content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(
    response['Content-Length'] = os.path.getsize(
    return response

temporary file should be deleted once the newfile object is evicted.

Removing tmp file after return HttpResponse in django-漫漫字节 , I'm using the following django/python code to stream a file to the browser: wrapper = FileWrapper(file(path))response = HttpResponse(wrapper,� 12 Removing tmp file after return HttpResponse in django Aug 27 '10. 0 Cannot solve mod_wsgi exception in Django setup Jan 22 '10. View all questions and answers →

Mostly, we use periodic cron jobs for this.

Django already has one cron job to clean up lost sessions. And you're already running it, right?


You want another command just like this one, in your application, that cleans up old files.

See this

Also, you may not really be sending this file from Django. Sometimes you can get better performance by creating the file in a directory used by Apache and redirecting to a URL so the file can be served by Apache for you. Sometimes this is faster. It doesn't handle the cleanup any better, however.

Removing tmp file after returning HttpResponse in django, You can use NamedTemporaryFile: from django.core.files.temp import NamedTemporaryFile def send_file(request): newfile = NamedTemporaryFile( suffix='.txt')� 9 Removing tmp file after return HttpResponse in django Aug 27 '10 7 Symfony2 / Doctrine: Reading “deleted” data when using Gedmo's doctrine extensions Jun 26 '14 6 Switching from Gulp to Webpack Jun 5 '17

This is just using the regular python approach (very simple example):

# something generates a file at filepath

from subprocess import Popen

# open file
with open(filepath, "rb") as fid:
    filedata =

# remove the file
p = Popen("rm %s" % filepath, shell=True)

# make response
response = HttpResponse(filedata, content-type="text/plain")

return response

Python Examples of django.http.FileResponse, Project: django-private-storage Author: edoburu File: License: size): return HttpResponseNotModified() # As of Django 1.8, FileResponse triggers Avoid reading the file at all response = HttpResponse() else: response else: ensure_created_by(problem, request.user) path = f"/tmp/{rand_str()}.zip" with zipfile. Django’s cache framework¶. A fundamental trade-off in dynamic websites is, well, they’re dynamic. Each time a user requests a page, the Web server makes all sorts of calculations – from database queries to template rendering to business logic – to create the page that your site’s visitor sees.

One way would be to add a view to delete this file and call it from the client side using an asynchronous call (XMLHttpRequest). A variant of this would involve reporting back from the client on success so that the server can mark this file for deletion and have a periodic job clean it up.

Python Examples of django.core.files.temp.NamedTemporaryFile, This page shows Python examples of django.core.files.temp. data_file, ' data_file', filename, content_type, size, charset=None) return media return None finally: file.close() tmp.flush() yield # Delete files when model is deleted 21)) # AttributeError: You cannot alter upload handlers after the upload� I'm new with python and Django. I know a lot about the Codeigniter framework and there if you want to create a project like an eCommerce you must create an admin panel with template and function for the backend. when I was creating backend I was adding functions for the admin panel where all functions were for adding some informations in the database. so when I start with Django I saw that

For future references: I just had the case in which I couldn't use temp files for downloads. But I still needed to delete them after it; so here is how I did it (I really didn't want to rely on cron jobs or celery or wossnames, its a very small system and I wanted it to stay that way).

def plug_cleaning_into_stream(stream, filename):
        closer = getattr(stream, 'close')
        #define a new function that still uses the old one
        def new_closer():
            #any cleaning you need added as well
        #substitute it to the old close() function
        setattr(stream, 'close', new_closer)

and then I just took the stream used for the response and plugged into it.

def send_file(request, filename):
    with, 'rb') as ready_file:
        plug_cleaning_into_stream(ready_file, filename)
        response = HttpResponse(, content_type='application/force-download')
        # here all the rest of the heards settings
        # ...
        return response

I know this is quick and dirty but it works. I doubt it would be productive for a server with thousands of requests a second, but that's not my case here (max a few dozens a minute).

EDIT: Forgot to precise that I was dealing with very very big files that could not fit in memory during the download. So that is why I am using a BufferedReader (which is what is underneath

Download a file on Django and delete it after return, a file and download it automatically for users, but I want to delete it after the file has been downloaded(after return the HttpResponse). I Created a Login Page in Django 'accounts' app, 1. whenever I enter username and password from Login Page, it should Authenticate using My Organization LDAP Server. 2. After Login I have to hold the session for the logged in user for 5 active minutes. (Django auth session) I saw django_auth_ldap package gives some insight for my purpose.

How to use sessions | Documentation de Django, To use file-based sessions, set the SESSION_ENGINE setting to most likely / tmp ) to control where Django stores session files. Be sure If value is an integer , the session will expire after that many seconds of inactivity. if request.session. get('has_commented', False): return HttpResponse("You've already commented. I publish my django website using gunicorn nginx and supervisor. as i read everywhere, this was the best setup for publishing django. everything is working fine. but then in my website i have this long requested script where it takes around 10 secs to finish. i noticed that while this script is loading, another request either its from the same computer or another computer, a simple html page

The messages framework | Django documentation, The messages framework can use different backends to store temporary DEBUG, Development-related messages that will be ignored (or removed) in a get_messages() will return an instance of the configured storage backend. To avoid the messages being cleared, you can set the messages storage to False after� I've tracked this problem down to the use of an empty regex in a URLConf. This is useful in order to include an application's urls with no prefix; i.e. something like this at the end of a urlpatterns:

Django Utils | Django documentation, All other parameters are added with their value, after applying str() to it. get_max_age (response)�. Returns the max-age from the response Cache- Control header as an integer (or Adds some useful headers to the given HttpResponse object: Outputs the feed in the given encoding to outfile , which is a file-like object. I get TemplateSyntaxError at /admin/ after updating to current this AM, isolated to being introduced in ; backing up to makes it go away. Full cut-and-paste info:

  • temporary file should be deleted once the newfile object is evicted: is there a built-in mechanism to automatically delete NamedTemporaryFile instances?
  • if I'm correct, objects are destroyed by the garbage collector once all references to it are destroyed. When you step out of the send_file function, there should be no more reference to the newfile object, hence it could be removed the next time the GC runs. The destructor of NamedTemporaryFile states: def close(self): if not self.close_called: self.close_called = True self.file.close() self.unlink( def __del__(self): self.close()
  • fylb, you're right, but it's not guaranteed that the object will be garbage-collected and its del method called. Who knows what the garbage collector will do? Better to clean up manually periodically.
  • Instead of redirecting, you can use mod xsendfile with Apache, then it's one request and you can control file access.
  • Doesn't sound like a good idea to me - there's no need for an additional message from the client to the server. Cleaning up the temp files periodically is much better.
  • @loevborg: The OP asked for alternatives. Hence. I could just make a cron to delete all tmp files, but it would be neater ...
  • please provide some explanation for your answer and avoid posting code only answers.