gpt4 book ai didi

python - Django 文件对象的 Python 等价物是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:27 25 4
gpt4 key购买 nike

我需要在 Python 中修改文件的 HTTP header ,我知道这可以使用 Django 的"file"对象 ( https://docs.djangoproject.com/en/dev/topics/files/ ),如我在此处关注的示例中所述:http://tmanstwobits.com/convert-your-web-pages-to-pdf-files-using-phantomjs.html

这是我在没有 Django 的情况下尝试复制的基本代码:

file_name = '/tmp/current_page.pdf'
url = ('user_current_url')
external_process = Popen(["phantomjs", phantomjs_script, url, file_name],
stdout=PIPE, stderr=STDOUT)
# Open the file created by PhantomJS
return_file = File(open(file_name, 'r'))
response = HttpResponse(return_file, mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=current_page.pdf'
# Return the file to the browser and force it as download item
return response

我试过使用 urllib.urlopen,它允许我修改 HTTP header ,但我遇到了其他问题,这似乎不是最好的方法。我怎样才能做到这一点?

最佳答案

由于您使用的是 Tornado,因此您必须设置一个请求处理程序:

import tornado.ioloop
import tornado.web

class PDFHandler(tornado.web.RequestHandler):
def get(self):
filename = 'current_page.pdf'

self.set_header('Content-Disposition', 'attachment; filename=current_page.pdf')
self.set_header('Content-Type', 'application/force-download')

with open(filename, 'r') as handle:
data = handle.read()
self.set_header('Content-Length', len(data))
self.write(data)

if __name__ == "__main__":
application = tornado.web.Application([
(r'/', PDFHandler),
])

application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

我会使用 tempfile 模块而不是对路径进行硬编码。此外,如果您担心内存使用情况,以 block 的形式流式传输文件会很好。

关于python - Django 文件对象的 Python 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com