![]() |
A Python framework that is used for building APIs is called FastAPI. There are some circumstances when the user needs to identify a certain event that happened in the API. This can be done using event handlers in FastAPI. In this article, we will study the various event handlers available in FastAPI. What is Event Handler in FastAPI?In FastAPI, an event handler is a Python function that is executed automatically when specific events occur during the execution of your application. These event handlers allow you to perform custom actions or modify the behavior of your FastAPI application at different stages of its lifecycle. Event handlers are often used to set up database connections, perform cleanup operations, or customize request and response behaviors. Types of FastAPI Event Handlers
FastAPI Startup EventThe Startup is the event triggered whenever the user starts the FastAPI app using the following command: uvicorn main:app --reload
This event is basically handled to declare the variables that should be up at the start of the app. It uses the on_event function available in FastAPI to judge the event trigger.
Example: In this example, we have created a function event_startup, that gets triggered on the start of the FastAPI app and prints the date and time when the app has started. Python3
Output: FastAPI Shutdown EventThe Shutdown is the event triggered whenever the user closes the FastAPI app using Ctrl and C keyboard buttons together. This event is basically handled to close any indefinite action being performed that should be ended at the close of the app. It uses the on_event function available in FastAPI to judge the event trigger.
Example: In this example, we have created a function event_shutdown, that gets triggered on the close of the FastAPI app and prints the date and time when the app has been shutdown. Python3
Output: Now, press Ctrl+C to see the shutdown event being triggered. |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |