Python Falcon - CORS



"Cross-Origin Resource Sharing" (CORS) is a situation when a frontend application that is running on one client browser tries to communicate with a backend through JavaScript code, and the backend is in a different "origin"than the frontend. The origin here is a combination of protocol, domain name and port numbers. As a result, http://localhost and https://localhost have different origins.

If the browser with URL of one origin sends request for execution of JavaScript code from another origin, the browser sends OPTIONS http request. If the backend authorizes the communication from this different origin by sending the appropriate headers it will let the JavaScript in the frontend send its request to the backend.

To enable the CORS policy for all responses, the Falcon app is configured as follows −

from falcon import App
app=App(cors_enable=True)

To specify explicitly the allowed origins, import CORSMiddleware and add the list of origins to the app's middleware, along with respective credentials.

from falcon import App
app = falcon.App(middleware=falcon.CORSMiddleware(allow_origins='example.com', allow_credentials='*')
Advertisements