Home >Backend Development >Python Tutorial >How to Efficiently Initialize and Reuse Global Objects in FastAPI Endpoints?
In FastAPI, you may encounter scenarios where initialising global objects or variables in every endpoint can be resource-intensive. Connections to external services or complex calculations are classic examples. This article provides two options for initialising and reusing global resources in FastAPI endpoints efficiently.
FastAPI allows you to store custom objects in the app.state attribute of the FastAPI app instance. This attribute can be accessed using the request.app.state property in endpoint functions. By initialising the global object in a startup event or lifespan function and adding it to app.state, all endpoints can access and reuse the object without the need for multiple initialisations.
The Starlette framework provides a lifespan handler that allows you to execute code before and after the application starts and shuts down. You can instantiate the global object in the lifespan handler and add it to the lifespan state dictionary. By using request.state in endpoint functions, you can access and reuse the object in endpoints.
Both options provide efficient mechanisms for initialising and reusing global objects in FastAPI. The choice depends on the specific requirements and preferences of your application.
The above is the detailed content of How to Efficiently Initialize and Reuse Global Objects in FastAPI Endpoints?. For more information, please follow other related articles on the PHP Chinese website!