I have a view that suddenly stopped working. Obviously something must have changed but i have no idea what.

the view is supposed to return a pdf file (ie. content-disposition is attachment) when the view is called, the browser tries to download a pdf, but no matter what it is always 0 bytes.

I've logging here and there to debug what the issue is. I can see that when the response object is returned from generate_pdf it has the correct contents. Somehow between there and the client browser, it simply disappears.

Anybody have any ideas?

django 1.3, nginx, uwsgi

views.py

def get(self, request, *args, **kwargs):
    ...
    return generate_pdf(request, 'ps_pdfbase.html', context_dict, returned_file_name)

generate_pdf function

...
myfile = StringIO()
result_obj = pisa.CreatePDF(file_data, myfile)

logging.debug('pdf result_obj:\n\tsize:%s\n\terr:%s\n\tlog:%s\n\ttext:%s' % (myfile.tell(),
                                                                                result_obj.err,
                                                                                result_obj.log,
                                                                                result_obj.text, )) 
myfile.seek(0)
response =  HttpResponse(myfile, mimetype='application/pdf')    
logging.debug('response content: %s' % response.content)
response['Content-Disposition'] = 'attachment; filename=' + slugify(returned_file_name) + '.pdf'
return response
有帮助吗?

解决方案

Just as an alterative approach try creating the response, then passing it directly to pisa?

response = http.HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
pisa.CreatePDF(file_data, response) 
return response

Have you decided against saving the file and serving it through Nginx X-Accel-Redirect? - Just for completeness here's an example of that:

Django view:

resp = http.HttpResponse()
resp['Content-Type'] = 'application/pdf'
resp['Content-Disposition'] = 'attachment; filename=filename.pdf'
resp['X-Accel-Redirect'] = '/xaccel_path/%s' % relative_path_to_file
return resp

nginx config:

server { 
...
location /xaccel_path {
internal;
alias /path/to/protected/files/;
}
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top