gpt4 book ai didi

python - 如何将修改响应正文的 WSGI 中间件添加到 AppEngine

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:26 25 4
gpt4 key购买 nike

添加一个仅修改 HTTP header 的中间件(如 FirePython)非常简单,但是当您调用 webapp.WSGIApplication(environ, start_response) 时,它会返回 [''] 而不是带有正文的可迭代对象:

def __call__(self, environ, start_response):
...
response.wsgi_write(start_response)
return ['']

response.wsgi_write 实际上是负责打印正文:

def wsgi_write(self, start_response):
...
write = start_response('%d %s' % self.__status, self.__wsgi_headers)
write(body)
self.out.close()

这使得通过 WSGI 中间件修改主体变得困难。通常我会这样做:

class Upperware:
def __init__(self, app):
self.wrapped_app = app

def __call__(self, environ, start_response):
for data in self.wrapped_app(environ, start_response):
return data.upper()

但这不起作用,因为 wrapped_app 的返回值是 ['']。如何让 Upperware 中间件在 Google AppEngine 中工作?导致写入响应而不是返回响应的设计决策是什么?

最佳答案

如果要拦截对请求正文的写入,则需要定义自己的start_responsewrite 函数,如下所示:

class Upperware(object):
def __init__(self, app):
self.wrapped_app = app

def __call__(self, environ, start_response):
def my_start_response(status, response_headers, exc_info=None):
write = start_response(status, response_headers, exc_info)
def my_write(body_data):
# Do your middleware handling of writes here
body_data = body_data.upper()
write(body_data)
return my_write
return self.wrapped_app(environ, my_start_response)

至于webapp为什么要这样写,恐怕我也不好说。应该可以更改其行为以生成迭代器或列表,而不会破坏任何东西,所以请随意 file a bug .

关于python - 如何将修改响应正文的 WSGI 中间件添加到 AppEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4411061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com