在Pyramid框架中,修改Response默认Content-Type的正确方式是什么?
修改Pyramid Response默认Content-Type的正确方法
当然有啦!在Pyramid框架里修改Response默认Content-Type有好几种靠谱的方式,你用tween的思路完全走对了,这是个全局生效的好方案,我给你把细节补全,再介绍其他几种常用方法:
方法一:用Tween全局修改(你提到的方案)
Tween是Pyramid里用来在请求处理前后插入自定义逻辑的机制,用来做这种全局的Response格式调整特别合适。完整的实现代码如下:
首先在你的项目里新建一个tweens.py文件:
class XhtmlTween: def __init__(self, handler, registry): self.handler = handler self.registry = registry def __call__(self, request): # 先让请求正常走完处理流程拿到响应 response = self.handler(request) # 只针对原本是text/html的响应修改,避免影响JSON、图片这类其他响应 if response.content_type == 'text/html': response.content_type = 'application/xhtml+xml' return response
然后在项目的配置文件(比如__init__.py)里注册这个tween:
config.add_tween('app.tweens:XhtmlTween')
这个方法的优势是全局生效,所有返回text/html的响应都会被自动改成application/xhtml+xml,不用在每个视图里重复写代码。
方法二:自定义Response工厂
如果你想从根源上改变默认的Response类型,可以自己写个Response工厂替换Pyramid自带的:
from pyramid.response import Response def xhtml_response_factory(request): # 创建默认Response对象时直接设置Content-Type response = Response() response.content_type = 'application/xhtml+xml' return response # 在配置里注册这个工厂 config.set_response_factory(xhtml_response_factory)
这种方式会让所有新建的Response对象默认就带着你要的Content-Type,不过要注意,如果视图里手动指定了content_type,会覆盖这个默认值。
方法三:针对视图/渲染器单独配置
如果不需要全局修改,只是部分视图需要调整的话,直接在视图里设置就行:
from pyramid.response import Response def my_xhtml_view(request): response = Response('<html><body>Hello XHTML</body></html>') response.content_type = 'application/xhtml+xml' return response
要是用的是Chameleon这类模板渲染器,也可以在渲染时直接指定:
return render_to_response( 'templates/mytemplate.pt', {'data': some_data}, request, content_type='application/xhtml+xml' )
总结一下:全局改的话,tween或者自定义Response工厂最省心;局部改的话,直接在视图或渲染器里指定就好。
内容的提问来源于stack exchange,提问作者ohmu
相关产品推荐
相关产品推荐

