![]() |
VOOZH | about |
In Falcon, hooks are type of callbacks that are defined by the user and are executed before or after a responder method in a particular resource class to process client request. They are useful in as much as they allow a client to add or overwrite request processing functionality at certain predefined stages.
Falcon offers two types of hooks:
Executed before the corresponding responder method is invoked. They are ideal for tasks such as:
They should be called after the responder method is done with the request processing. They are typically used for:
Falcon provides two decorators, @falcon.before and @falcon.after, for hanging callbacks on responder methods, or indeed on whole classes of resources. The arguments passed to hook functions include:
req (falcon. Request): The current HTTP request object with each of the typically included objects in the request being defined as a property of the HTTP request object.
resp (falcon. Response): This is the current HTTP response instance used for the current request.
resource (object): The resource class instance of the particular request that the customer or the client wants to access.
params (dict): This is the portion of the URI template either consisting of field names and corresponding values when they are present.
Let's create a simple example where we use a before hook to check for an authentication token in the request headers.
Firstly, install Falcon if you haven't installed already:
pip install falconCreate a file named app.py and start by importing the necessary modules and writing the hook function:
Next, define a resource where the hook will be applied:
ResourceWithAuth is a resource class with two methods:
Set up the Falcon API and add the route:
Run your Falcon application, using:
python app.pyYou should see the output indicating that the server is running:
Let's test our before hook using curl:
curl -i http://localhost:8000/securecurl -i -H "Authorization: secret-token" http://localhost:8000/secureOutput:
After hooks are defined similarly but are used to modify the response:
ResourceWithAfterHook is a resource class with two methods:
The @falcon.after(add_custom_header) decorator applies the add_custom_header hook to both methods.
This block of code checks if the script is being run directly.
It uses Python's built-in WSGI server to serve the Falcon application on port 8000.
To test the application and see the logging in action, you can use curl or any other HTTP client:
curl -i http://localhost:8000/customcurl -i -X POST http://localhost:8000/customYou can apply multiple hooks to a resource. Just chain them together using the Falcon decorators:
@falcon.before(auth_hook)
@falcon.before(another_hook)
class AnotherResource:
def on_get(self, req, resp):
resp.media = {'message': 'Multiple hooks applied!'}
By using Falcon hooks, we achieve clean separation of concerns, making our code more modular and easier to maintain.
Before hooks can be used to enforce some certain levels of authentication and authorization mechanisms by checking user credentials or tokens before granting the users access to the protected resources.
When using hooks, after hooks in particular are usually followed by logging of the request and response details, including request method, URL, status, as well as execution time for diagnostics and control purposes.
Before hooks can get a hold of incoming requests to check whether they meet specific criteria, it is essential to understand that all requests shall meet certain requirements like required parameters, data types, or format.
Next paradigms allow hooks so that the actual content of the response, or the headers in which it is returned to the client, can be changed according to certain needs.
Both before and after hooks can be used for caching strategies For the before hooks can check if it is there a cached response then it will immediately serve it , whereas after hooks can cache the response generated now to serve it in future similar requests.
After hooks are discussed as a tool to capture metrics which are typically associated with API utilization for monitoring and optimization purposes such as the number of requests to the API, time taken to process requests, number of errors, etc.