Skip to main content
 首页 » 编程设计

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

2025年05月04日26java哥

我需要在 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 的形式流式传输文件会很好。