2020-09-02 04:58:13 +03:00
|
|
|
"""`Singleton` - Flask request scope example."""
|
2020-09-01 23:04:48 +03:00
|
|
|
|
2020-09-03 23:56:01 +03:00
|
|
|
from dependency_injector import containers, providers
|
|
|
|
from flask import Flask, current_app
|
2020-09-01 23:04:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
2020-09-03 23:56:01 +03:00
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
2021-03-30 22:58:39 +03:00
|
|
|
service_provider = providers.ThreadLocalSingleton(Service)
|
2020-09-01 23:04:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
def index_view():
|
2020-09-03 23:56:01 +03:00
|
|
|
service_1 = current_app.container.service_provider()
|
|
|
|
service_2 = current_app.container.service_provider()
|
2020-09-01 23:04:48 +03:00
|
|
|
assert service_1 is service_2
|
|
|
|
print(service_1)
|
2021-09-30 22:32:21 +03:00
|
|
|
return "Hello World!"
|
2020-09-01 23:04:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
def teardown_context(request):
|
2020-09-03 23:56:01 +03:00
|
|
|
current_app.container.service_provider.reset()
|
2020-09-01 23:04:48 +03:00
|
|
|
return request
|
|
|
|
|
|
|
|
|
2020-09-03 23:56:01 +03:00
|
|
|
container = Container()
|
|
|
|
|
2020-09-01 23:04:48 +03:00
|
|
|
app = Flask(__name__)
|
2020-09-03 23:56:01 +03:00
|
|
|
app.container = container
|
2021-09-30 22:32:21 +03:00
|
|
|
app.add_url_rule("/", "index", view_func=index_view)
|
2020-09-01 23:04:48 +03:00
|
|
|
app.after_request(teardown_context)
|
|
|
|
|
2020-09-02 04:58:13 +03:00
|
|
|
|
2021-09-30 22:32:21 +03:00
|
|
|
if __name__ == "__main__":
|
2020-09-01 23:04:48 +03:00
|
|
|
app.run()
|