Search code examples
pythonroutesmiddlewarefalconframework

Routing with python Falcon


I am new to Falcon framework of python. I have a question regarding the usage of middleware class of Falcon. Is it wise to use custom routers and authentication of requests in the middleware or should this be handled only on the routing

**main.py**

import falcon
import falcon_jsonify
import root
from waitress import serve

if __name__ == "__main__":
    app = falcon.API(
        middleware=[falcon_jsonify.Middleware(help_messages=True),
        root.customRequestParser()]
    )
    serve(app, host="0.0.0.0", port=5555)

root.py where I am planning to write the custom routes

import json
import falcon

class Home(object):
    @classmethod
    def getResponse(self):
        return {"someValue": "someOtherValue"}

def process_request_path(path):
    path = path.lstrip("/").split("/")
    return path

class customRequestParser(object):
    def process_request(self, req, resp):
        print process_request_path(req.path)

I also saw examples using app = falcon.API(router=CustomRouter()). I saw a documentation on the falcon official documentation page - http://falcon.readthedocs.io/en/stable/api/routing.html

Please let me know if there are any references that I can look through.


Solution

  • To quote the Falcon Community FAQ

    How do I authenticate requests?

    Hooks and middleware components can be used together to authenticate and authorize requests. For example, a middleware component could be used to parse incoming credentials and place the results in req.context. Downstream components or hooks could then use this information to authorize the request, taking into account the user’s role and the requested resource.

    Falcon's Hooks are decorators used on the either a particular request function (i.e. on_get) or on an entire class. They're great for validating incoming requests, so as the FAQ says, authentication could be done at this point.

    Here's an (untested) example I knocked up:

    def AuthParsingMiddleware(object):
        def process_request(self, req, resp):
            req.context['GodMode'] = req.headers.get('Auth-Token') == 'GodToken':
        # Might need process_resource & process_response     
    
    def validate_god_mode(req, resp, resource, params):
        if not req.context['GodMode']:
            raise falcon.HTTPBadRequest('Not authorized', 'You are not god')
    
    
    def GodLikeResource(object):
        @falcon.before(validate_god_mode):
        def on_get(self, req, resp):
            resp.body = 'You have god mode; I prostrate myself'
    
    
    app = falcon.API(
        middleware=[falcon_jsonify.Middleware(help_messages=True),
                    AuthParsingMiddleware()]
    )
    app.add_route('/godlikeresource', GodLikeResource())
    

    Or better...

    There is a falcon-auth package.