Search code examples
pythonpython-3.xpyramid

Proper way to change the default Response content-type


In Pyramid, is there a proper way to change the default Response content-type? I figured out I can do it by using a tween to change the content-type from 'text/html' to 'application/xhtml+xml'.

config.add_tween('app.tweens:XhtmlTween')
class XhtmlTween(object):

    def __init__(self, handler, registry):
        self.handler = handler
        self.registry = registry

    def __call__(self, request):
        # Process request.
        response = self.handler(request)

        # Change content-type.
        # - Taken from JSON.__call__ from <https://github.com/Pylons/pyramid/blob/master/pyramid/renderers.py>.
        if response.content_type == response.default_content_type:
            response.content_type = 'application/xhtml+xml'

        return response

However, this looks like an awful hack. Is there a better way to do this?


Solution

  • From the Pyramid docs, "Request and Response Objects" under Instantiating the Response:

    You can subclass pyramid.response.Response and set default_content_type to override this behavior.