从Django返回stdout的pdf响应 [英] return pdf response from stdout with Django
本文介绍了从Django返回stdout的pdf响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用wkhtmltopdf创建PDF文件,我怎么不知道如何正确地返回它们,所以我不得不将它们写入我的媒体文件夹,然后重定向到刚创建的文件。
I am using wkhtmltopdf to create PDF files, how ever I don't know how to return them properly, so I had to write them to my media folder and then redirect to the just created file.
编辑:
Ian的建议是写入STDOUT,所以我改变了我的wkhtmltopdf命令,但现在我不知道如何返回那个内容。
Ian's advice is to write to STDOUT, so I have changed my wkhtmltopdf command to do that, but now I don't know how to return that content.
我一直在尝试使用subprocess.Popen这样:
I have been trying using subprocess.Popen this way:
r = HttpResponse(Popen(command_args), mimetype='application/pdf')
r['Content-Disposition'] = 'filename=recibos.pdf'
return r
但我没有得到好的结果
提前感谢
But I am not getting good results Thanks in advance.
推荐答案
你应该像这样打开你的子命令:
You should open your sub command like so:
popen = Popen(command_args, stdout=PIPE, stderr=PIPE)
body_contents = popen.stdout().read()
popen.terminate()
popen.wait()
r = HttpResponse(body_contents, mimetype='application/pdf')
有些事情要小心:
- 如果popen'd命令写入STDERR,它可能会死锁。你可以通过在Popen对象上使用communic()函数来解决这个问题。
- 你应该尝试这样做,以确保总是终止()和wait()。
- 将整个PDF加载到您的python进程的内存中,您可能需要将命令中的字节流传送到传出的套接字。
这篇关于从Django返回stdout的pdf响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文