- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - FastAPI Event Handlers
Event handlers are the functions to be executed when a certain identified event occurs. In FastAPI, two such events are identified − startup and shutdown. FastAPI’s apppcation object has on_event() decorator that uses one of these events as an argument. The function registered with this decorator is fired when the corresponding event occurs.
The startup event occurs before the development server starts and the registered function is typically used to perform certain initiapzation tasks, estabpshing connection with the database etc. The event handler of shutdown event is called just before the apppcation shutdown.
Example
Here is a simple example of startup and shutdown event handlers. As the app starts, the starting time is echoed in the console log. Similarly, when the server is stopped by pressing ctrl+c, the shutdown time is also displayed.
main.py
from fastapi import FastAPI import datetime app = FastAPI() @app.on_event("startup") async def startup_event(): print( Server started : , datetime.datetime.now()) @app.on_event("shutdown") async def shutdown_event(): print( server Shutdown : , datetime.datetime.now())
Output
It will produce the following output −
uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for apppcation startup. Server started: 2021-11-23 23:51:45.907691 INFO: Apppcation startup complete. INFO: Shutting down INFO: Waiting for apppcation server Shutdown: 2021-11-23 23:51:50.82955 INFO: Apppcation shutdown com INFO: Finished server processAdvertisements