Python Falcon Part 6 - Learn how to use hooks

Support my channels

Hooks in Falcon is its a trigger you can handle before and after your single function, i'm using it normal to define witch version of a function i want to trigger but i use it also to control about the user have the right access and if its not have it, i want to not allow the access to a single micro services.

In this tutorial i want to show you how you can get happy by using hook when you code with Falcon in Python.

import falcon

class Authorize(object):
    def __init__(self, roles):
        self._roles = roles

    def __call__(self, req, resp, resource, params):
        if 'Admin' in self._roles:
            req.user_id = 5

            raise falcon.HTTPBadRequest('Bad request', 'Your are not a admin right now')

class ObjResource:
    def on_get(self, req, resp):
        print('trigger - get')

        output = {
            'method': 'get',
            'user-id': req.user_id
        } = output

    def on_post(self, req, resp):
        print('trigger - post')

        output = {
            'method': 'post',
            'user-id': req.user_id
        } = output

api = falcon.API()
api.add_route('/account', ObjResource())

Similar video courses