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