繁体   English   中英

Python与Django File对象等效吗?

[英]What is the Python equivalent to Django File object?

我需要在Python中修改文件的HTTP标头,并且我知道可以使用Django的“文件”对象( 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标头,但遇到其他问题,它似乎不是最佳方法。 我该怎么做?

由于您正在使用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模块而不是对路径进行硬编码。 另外,如果您担心内存使用情况,则分块传输文件会很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM