Skip to content

Instantly share code, notes, and snippets.

@particledecay
Created February 25, 2013 17:29
Show Gist options
  • Save particledecay/f69f274664e806d27a73 to your computer and use it in GitHub Desktop.
Save particledecay/f69f274664e806d27a73 to your computer and use it in GitHub Desktop.
Simple direct download view using x-sendfile.
def direct_download(request):
"""
Returns a file path via X-Sendfile that the webserver will serve as a regular file (vs a rendered page).
Note: The webserver needs to support this header (i.e., Apache + mod_xsendfile)... Django dev server doesn't.
"""
if request.method == 'GET':
song_slug = request.GET.get('slug')
if song_slug:
song = get_object_or_404(Song, slug=song_slug)
else:
raise Http404
filename = os.path.basename(song.path.name)
response = HttpResponse(mimetype='audio/mpeg')
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
response['X-Sendfile'] = smart_str(song.path.name)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment