我有以下代码:
def application(env, start_response):
path = process(env)
fh = open(path,'r')
start_response('200 OK', [('Content-Type','application/octet-stream')])
return fbuffer(fh,10000)
def fbuffer(f, chunk_size):
'''Generator to buffer file chunks'''
while True:
chunk = f.read(chunk_size)
if not chunk: break
yield chunk
我不确定这是否正确,但我在互联网上找到的零碎信息使我认为它应该起作用。基本上,我想将一个文件分块流式输出,为此,我从应用程序函数中传递一个生成器。不过,这只打印出标题,实际上并没有发送任何数据,有人能告诉我为什么会这样吗?在
或者,如果这是完全错误的,最好的方法是什么?我无法在内存中缓冲整个文件,因为我要处理的文件可能有千兆字节大。在
第三个问题:输出完毕后,关闭文件的最佳方式是什么?在我发布的代码中,我看不到实际关闭文件。在
(我运行的是python3.2.3和uWSGI 1.2.4)
uwsgi非常小心,不允许错误泄漏到中,但是如果您在更严格的实现中运行应用程序,比如python提供的
wsgiref.simple_server
,您可以更容易地看到问题。在问题是wsgi要求传输到HTTP网关和从HTTP网关发送的数据必须作为
bytes
提供服务,但是当使用open(path, 'r')
时,python3很方便地将读取的数据转换为unicode,在python3中是str
,使用默认编码。在改变
^{pr2}$到
修复它。在
相关问题 更多 >
编程相关推荐