Falcon: Simple way to allow all CORS / OPTIONS requests?

Created on 6 Feb 2018  路  3Comments  路  Source: falconry/falcon

I'm wanting to open the door wide to all CORS requests to my application.

I can see there is an additional Falcon/CORS middleware project but I'm hoping there is some simpler way to just open the door wide with a few lines of code and no need to worry about understanding and implementing the middleware and the various options and fine tuning that it provides.

Any suggestions for how to do this?

Most helpful comment

Answering my own question:

import falcon
from falcon.http_status import HTTPStatus

class HandleCORS(object):
    def process_request(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', '*')
        resp.set_header('Access-Control-Allow-Headers', '*')
        resp.set_header('Access-Control-Max-Age', 1728000)  # 20 days
        if req.method == 'OPTIONS':
            raise HTTPStatus(falcon.HTTP_200, body='\n')

wsgi_app = api = falcon.API(middleware=[HandleCORS() ])

All 3 comments

Answering my own question:

import falcon
from falcon.http_status import HTTPStatus

class HandleCORS(object):
    def process_request(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', '*')
        resp.set_header('Access-Control-Allow-Headers', '*')
        resp.set_header('Access-Control-Max-Age', 1728000)  # 20 days
        if req.method == 'OPTIONS':
            raise HTTPStatus(falcon.HTTP_200, body='\n')

wsgi_app = api = falcon.API(middleware=[HandleCORS() ])

It seems you have coined a solution that fits your needs :smiling_imp:

Your question is otherwise actually answered in the FAQ [1], and the answer is really fairly similar to yours. Note the suggestion handles 'OPTIONS' in a slightly different way (by telling which methods are supported instead of saying "all methods"), but yours would do too.

  1. https://falcon.readthedocs.io/en/stable/user/faq.html#how-do-i-implement-cors-with-falcon

Also note that a simple to way to add unsophisticated permissive CORS is under consideration to be included in Falcon 2.0: https://github.com/falconry/falcon/issues/1194

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jhuitema picture jhuitema  路  6Comments

neilalbrock picture neilalbrock  路  5Comments

coffeedoughnuts picture coffeedoughnuts  路  8Comments

xiaodi007 picture xiaodi007  路  4Comments

bachrc picture bachrc  路  3Comments