Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
drnextgis Avatar asked Jan 14 '14 06:01

drnextgis


1 Answers

There are several ways to do this: 1) a custom request factory like drnextgis showed, a NewRequest event handler, or a tween. A tween is almost certainly not the right way to do this, so I won't show that. Here is the event handler version:

def add_cors_headers_response_callback(event):
    def cors_headers(request, response):
        response.headers.update({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS',
        'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization',
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Max-Age': '1728000',
        })
    event.request.add_response_callback(cors_headers)

from pyramid.events import NewRequest
config.add_subscriber(add_cors_headers_response_callback, NewRequest)
like image 199
Wichert Akkerman Avatar answered Sep 22 '22 09:09

Wichert Akkerman