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):
|
|
|
|
|
|
|
|
service_provider = providers.Singleton(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)
|
|
|
|
return 'Hello World!'
|
|
|
|
|
|
|
|
|
|
|
|
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
|
2020-09-01 23:04:48 +03:00
|
|
|
app.add_url_rule('/', 'index', view_func=index_view)
|
|
|
|
app.after_request(teardown_context)
|
|
|
|
|
2020-09-02 04:58:13 +03:00
|
|
|
|
2020-09-01 23:04:48 +03:00
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run()
|