Login

send_file and send_data

Author:
danjak
Posted:
March 11, 2007
Language:
Python
Version:
Pre .96
Score:
2 (after 2 ratings)

Simple functions for downloading files - send_data sends the data directly, send_file as attachment. May need optimizing for large files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.http import HttpResponse

import os, mimetypes

def send_data(path, filename = None, mimetype = None):

    if filename is None: filename = os.path.basename(path)
    
    if mimetype is None:
        mimetype, encoding = mimetypes.guess_type(filename)
    
    response = HttpResponse(mimetype=mimetype)
    response.write(file(path, "rb").read())
    return response
    
def send_file(path, filename = None, mimetype = None):

    if filename is None: filename = os.path.basename(path)

    if mimetype is None:
        mimetype, encoding = mimetypes.guess_type(filename)
    
    response = HttpResponse(mimetype=mimetype)
    response['Content-Disposition'] = 'attachment; filename=%s' %filename
    response.write(file(path, "rb").read())
    return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.