2020-10-30 05:55:09 +03:00
|
|
|
"""`Resource` - Flask request scope example."""
|
|
|
|
|
|
|
|
from dependency_injector import containers, providers
|
2021-09-30 22:03:19 +03:00
|
|
|
from dependency_injector.wiring import Closing, Provide, inject
|
2020-10-30 05:55:09 +03:00
|
|
|
from flask import Flask, current_app
|
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
def init_service() -> Service:
|
2021-09-30 22:03:19 +03:00
|
|
|
print("Init service")
|
2020-10-30 05:55:09 +03:00
|
|
|
yield Service()
|
2021-09-30 22:03:19 +03:00
|
|
|
print("Shutdown service")
|
2020-10-30 05:55:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
service = providers.Resource(init_service)
|
|
|
|
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
@inject
|
2020-10-30 05:55:09 +03:00
|
|
|
def index_view(service: Service = Closing[Provide[Container.service]]):
|
|
|
|
assert service is current_app.container.service()
|
2021-09-30 22:03:19 +03:00
|
|
|
return "Hello World!"
|
2020-10-30 05:55:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
container = Container()
|
2021-09-30 22:03:19 +03:00
|
|
|
container.wire(modules=[__name__])
|
2020-10-30 05:55:09 +03:00
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
app.container = container
|
2021-09-30 22:03:19 +03:00
|
|
|
app.add_url_rule("/", "index", view_func=index_view)
|
2020-10-30 05:55:09 +03:00
|
|
|
|
|
|
|
|
2021-09-30 22:03:19 +03:00
|
|
|
if __name__ == "__main__":
|
2020-10-30 05:55:09 +03:00
|
|
|
app.run()
|