在服务器端我有生成pdf文件的功能:
def get_pdf(template, context_dict):
context = Context(context_dict)
html = template.render(context)
import subprocess
wkhtml2pdf = subprocess.Popen((settings.WKHTML2PDF_COMMAND,
"--encoding",
"UTF-8",
"-",
"-"),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
wkdata = wkhtml2pdf.communicate(html.encode('utf8'))
pdf = wkdata[0];
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % (
timezone.now().strftime('%Y_%m_%d_%H_%M_%S')
)
response.write(pdf)
return response
我希望在返回响应之前将此文件保存在服务器端。怎么做?
答案 0 :(得分:3)
你想在哪里保存这个文件?我想在MEDIA_ROOT
:
import os
from django.conf import settings
...
pdf = wkdata[0];
file_name = os.path.join(settings.MEDIA_ROOT,
timezone.now().strftime('%Y_%m_%d_%H_%M_%S.pdf'))
with open(file_name, 'w') as f:
f.write(pdf)
response = HttpResponse(mimetype='application/pdf')
...