How to send file to response in Django?

Nurzhan Nogerbek picture Nurzhan Nogerbek · May 23, 2018 · Viewed 12.8k times · Source

I have such php function which I try to rewrite in my Django project. What should be an analogue in python for php methods like header() and show_error()? Also how to send file to response?

php:

function waprfile($date=false) {
    if(!isset($date) || $date==false) $date = date("d.m.y");

    $timestmp = date2timestamp($date);

    $filepath = "https://www.example.com/files/".$this->lang_code."/";

    if(file_get_contents($filepath.date("dmy",$timestmp).".xls"))
    {
        header("Location: ".$filepath."wapr".date("dmy",$timestmp).".xls");
    }
    else
    {
        show_error(_langWrite("No file for specified date", "Файл на указанную дату отсутствует"));
    }
}

python:

import urllib.request
import datatime
import time
from django.utils import translation

def isset(variable):
    return variable in locals() or variable in globals()

def waprfile(request, date):
    if(not isset(date) or date==False):
        date = datetime.datetime.now().strftime('%d.%m.%Y')

    timestmp = time.mktime(datatime.datetime.strptime(date, "%d.%m.%Y").timetuple())

    filepath = "https://www.example.com/files/" + str(translation.get_language()) + "/"

    formatted_date = datetime.datetime.fromtimestamp(timestmp).strftime('%d%m%y')

    if(urllib.request.urlopen(filepath + formatted_date + '.xls')):
        # What must be here?
    else:
        # What must be here?

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + fileName
    return response

Answer

Satendra picture Satendra · May 23, 2018

Read file first and then send it in response.

from django.http import HttpResponse, HttpResponseNotFound

def waprfile(request, date):
    ...

    file_location = '/path/to/file/foo.xls'

    try:    
        with open(file_location, 'r') as f:
           file_data = f.read()

        # sending response 
        response = HttpResponse(file_data, content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename="foo.xls"'

    except IOError:
        # handle file not exist case here
        response = HttpResponseNotFound('<h1>File not exist</h1>')

    return response

Read docs for more info: telling browser to treat the response as a file attachment and returning errors