使用gen的WSGI文件流

2024-09-30 16:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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)


Tags: 文件path代码envsizeapplicationresponsedef
1条回答
网友
1楼 · 发布于 2024-09-30 16:41:58

uwsgi非常小心,不允许错误泄漏到中,但是如果您在更严格的实现中运行应用程序,比如python提供的wsgiref.simple_server,您可以更容易地看到问题。在

Serving <function application at 0xb65848> http://0.0.0.0:8000
Traceback (most recent call last):
  File "/usr/lib64/python3.2/wsgiref/handlers.py", line 138, in run
    self.finish_response()
  File "/usr/lib64/python3.2/wsgiref/handlers.py", line 179, in finish_response
    self.write(data)
  File "/usr/lib64/python3.2/wsgiref/handlers.py", line 264, in write
    "write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance
localhost.localdomain - - [04/Aug/2012 16:27:08] "GET / HTTP/1.1" 500 59

问题是wsgi要求传输到HTTP网关和从HTTP网关发送的数据必须作为bytes提供服务,但是当使用open(path, 'r')时,python3很方便地将读取的数据转换为unicode,在python3中是str,使用默认编码。在

改变

^{pr2}$

fh = open(path, 'rb')
#                 ^

修复它。在

相关问题 更多 >