我编写了一个Python + WSGI应用程序,我想返回一个临时1xx状态代码,例如102" Processing"或103"早期提示"在返回最终的200和结果体之前,使用一些标题。
我知道,为了在几个步骤中返回数据,我的应用程序需要是可迭代的,例如yield(参见In WSGI, send response without returning)
但到目前为止,我发现的所有示例都只使用了一个状态代码。我发现无法改变它。例如,代码:
import wsgiref, wsgiref.simple_server, time
def app(environ, start):
start('102 Processing', [('Foo', 'bar')])
yield "More to come"
time.sleep(2)
start('200 OK', [('Content-Type', 'text/plain')])
yield "hello, world"
httpd = wsgiref.simple_server.make_server('localhost', 8999, app)
httpd.serve_forever()
仅发送102状态代码,并在发送其余内容时崩溃:
Exception happened during processing of request from ('127.0.0.1', 53540)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 290, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
self.handle()
File "/usr/lib/python2.7/wsgiref/simple_server.py", line 131, in handle
handler.run(self.server.get_app())
File "/usr/lib/python2.7/wsgiref/handlers.py", line 92, in run
self.close()
File "/usr/lib/python2.7/wsgiref/simple_server.py", line 33, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
WSGI中有没有办法做到这一点?
答案 0 :(得分:1)
没有。在WSGI应用程序级别,这是不可能的。
状态和标题只能在第一个响应内容产生之前更改,但此时还没有任何内容可以发送回客户端,因此无法用于发送多个状态和标题,仅替换将要发送的内容。