pythoncorspyramid

Pyramid CORS for Ajax requests


Is it possible automatically add Access-Control-Allow-Origin header to all responses which was initiated by ajax request (with header X-Requested-With) in Pyramid?


Solution

  • I've solved the problem using set_request_factory:

    from pyramid.request import Request
    from pyramid.request import Response
    
    def request_factory(environ):
        request = Request(environ)
        if request.is_xhr:
            request.response = Response()
            request.response.headerlist = []
            request.response.headerlist.extend(
                (
                    ('Access-Control-Allow-Origin', '*'),
                    ('Content-Type', 'application/json')
                )
            )
        return request
    
    config.set_request_factory(request_factory)