python-dependency-injector/examples/catalogs/bundles/catalogs.py

65 lines
2.0 KiB
Python
Raw Normal View History

2015-10-19 10:31:21 +03:00
"""Catalog bundles example."""
2015-11-20 14:46:57 +03:00
from dependency_injector import catalogs
from dependency_injector import providers
from dependency_injector import errors
2015-10-19 10:31:21 +03:00
import services
import views
# Declaring services catalog:
2015-11-20 14:46:57 +03:00
class Services(catalogs.DeclarativeCatalog):
2015-10-19 10:31:21 +03:00
"""Example catalog of service providers."""
2015-11-20 14:46:57 +03:00
users = providers.Factory(services.Users)
""":type: providers.Provider -> services.Users"""
2015-10-19 10:31:21 +03:00
2015-11-20 14:46:57 +03:00
auth = providers.Factory(services.Auth)
""":type: providers.Provider -> services.Auth"""
2015-10-19 10:31:21 +03:00
2015-11-20 14:46:57 +03:00
photos = providers.Factory(services.Photos)
""":type: providers.Provider -> services.Photos"""
2015-10-19 10:31:21 +03:00
# Declaring views catalog:
2015-11-20 14:46:57 +03:00
class Views(catalogs.DeclarativeCatalog):
2015-10-19 10:31:21 +03:00
"""Example catalog of web views."""
2015-11-20 14:46:57 +03:00
auth = providers.Factory(views.Auth,
services=Services.Bundle(Services.users,
Services.auth))
""":type: providers.Provider -> views.Auth"""
2015-10-19 10:31:21 +03:00
2015-11-20 14:46:57 +03:00
photos = providers.Factory(views.Photos,
services=Services.Bundle(Services.users,
Services.photos))
""":type: providers.Provider -> views.Photos"""
2015-10-19 10:31:21 +03:00
# Creating example views:
auth_view = Views.auth()
photos_view = Views.photos()
2015-11-04 17:32:04 +03:00
print auth_view.services # prints: <__main__.Services.Bundle(users, auth)>
print photos_view.services # prints <__main__.Services.Bundle(photos, users)>
2015-10-19 10:31:21 +03:00
# Making some asserts:
assert auth_view.services.users is Services.users
assert auth_view.services.auth is Services.auth
try:
auth_view.services.photos
2015-11-20 14:46:57 +03:00
except errors.Error:
2015-10-19 10:31:21 +03:00
# `photos` service provider is not in scope of `auth_view` services bundle,
# so `di.Error` will be raised.
pass
assert photos_view.services.users is Services.users
assert photos_view.services.photos is Services.photos
try:
photos_view.services.auth
2015-11-20 14:46:57 +03:00
except errors.Error as exception:
2015-10-19 10:31:21 +03:00
# `auth` service provider is not in scope of `photo_processing_view`
# services bundle, so `di.Error` will be raised.
pass