![]() |
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. Understanding Hooks in Python FalconFalcon offers two types of hooks: 1. Before HooksExecuted before the corresponding responder method is invoked. They are ideal for tasks such as:
2. After HooksThey should be called after the responder method is done with the request processing. They are typically used for:
Using HooksFalcon 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. Example: Authentication HookLet’s create a simple example where we use a before hook to check for an authentication token in the request headers. Step 1: Setting Up FalconFirstly, install Falcon if you haven’t installed already: pip install falcon Step 2: Writing the HookCreate a file named app.py and start by importing the necessary modules and writing the hook function:
Step 3: Creating a ResourceNext, define a resource where the hook will be applied:
ResourceWithAuth is a resource class with two methods:
Step 4: Setting Up the APISet up the Falcon API and add the route:
Running the ApplicationRun your Falcon application, using: python app.py You should see the output indicating that the server is running: ![]() output Testing the HookLet’s test our before hook using curl: Without Tokencurl -i http://localhost:8000/secure Output:![]() Output – Without token With Tokencurl -i -H "Authorization: secret-token" http://localhost:8000/secure Output: ![]() Output – With Token Example: Logging (After Hooks)After hooks are defined similarly but are used to modify the response: Setting Up Logging:
Defining the After Hook:
Creating the Resource with Request Handlers:
ResourceWithAfterHook is a resource class with two methods:
The @falcon.after(add_custom_header) decorator applies the add_custom_header hook to both methods. Setting Up the Falcon API and Adding the Route:
Running the Application:
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. Testing the After HookTo test the application and see the logging in action, you can use curl or any other HTTP client: GET Requestcurl -i http://localhost:8000/custom POST Requestcurl -i -X POST http://localhost:8000/custom Advanced Hook UsageMultiple HooksYou can apply multiple hooks to a resource. Just chain them together using the Falcon decorators: @falcon.before(auth_hook) By using Falcon hooks, we achieve clean separation of concerns, making our code more modular and easier to maintain. Common Use Cases for Falcon HooksAuthentication and Authorization: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. Logging: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. Request Validation: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. Response Manipulation: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. Caching: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. Metrics Collection: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. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 19 |