在Pylons中通过中间件修改头部信息

1 投票
1 回答
1203 浏览
提问于 2025-04-15 22:22

我正在尝试通过Pylons中的中间件来修改一个头部信息,以使我的应用程序符合RESTful风格。简单来说,就是如果用户通过GET请求"application/json",那么他就会收到这个格式的响应。

我有个问题,变量headers基本上是一个很长的列表,看起来像这样:

[('Content-Type', 'text/html; charset=utf-8'), ('Pragma', 'no-cache'), ('Cache-Control', 'no-cache'), ('Content-Length','20'), ('Content-Encoding', 'gzip')]

现在,我想根据请求来修改这个值,但这些位置是固定的吗?'Content-Type'总是会在headers[0][0]这个位置吗?

最好的祝愿,

安德斯

1 个回答

1

试试这个


from webob import Request, Response
from my_wsgi_application import App
class MyMiddleware(object):
    def init(self, app):
        self.app = app
    def call(self, environ, start_response):
        req = Request(environ)
... rsp = req.get_response(app) rsp.headers['Content-type'] = 'application/json' return rsp(environ, start_response)

或者在你的控制器里简单地把请求或响应的 .headers['Content-type'] 设置为 'application/json'

查看 http://pythonpaste.org/webob/reference.html#headers

撰写回答