Home >Backend Development >Python Tutorial >How to Efficiently Initialize and Reuse Global Objects in FastAPI Endpoints?

How to Efficiently Initialize and Reuse Global Objects in FastAPI Endpoints?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 01:22:10933browse

How to Efficiently Initialize and Reuse Global Objects in FastAPI Endpoints?

Initialising and Reusing Global Objects in FastAPI Endpoints

Overview

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.

Option 1: Using the Request Object

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.

Option 2: Using the Starlette Lifespan Handler

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.

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn