'Dependency Injections and Design Patterns in Python
I have been following examples from the official dependency injection here - https://python-dependency-injector.ets-labs.org/examples/application-single-container.html#services - and I implemented in my Flask service.
What I've noticed that every API request creates a new service object (providers.Factory). My service relied on S3 datastore which is defined as a providers.Resource
All my service does is returns values (just a couple of GET methods, that's all). The app doesn't expect a lot of traffic (possibly 100 requests a day scattered over 24h) and every API invocation creates a new service object (which is injected with the S3 providers.Resource.
Is this the right way to do? The Resource creates a single instance (akin to Singleton) but has intialize & shutdown methods to manage it. This is what my code looks like:
s3_repository = providers.Resource(
S3Repository, config.app.my_service.s3_bucket
)
my_service = providers.Factory(
MyService, config, s3_repository
)
The S3 client also periodically fetches data (once every day) and every new instance of my_service does not have fresh data if the same s3 client hasn't run the periodic job. Would it make sense to change my_service to a provider.Singleton? This service shall only read data, no updates/inserts/deletes ever.
my_service is instantiated on every API request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
