如何将响应保存到文件?

How to save response to file?

在服务器端我有生成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

而且我想在 return 响应之前将此文件保存在服务器端。怎么做?

你想把这个文件保存在哪里?我想在 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')
...