Objects that are commonly used in each view of the Pyramid app can be defined smartly by using the Root Object mechanism.
class RootResource(object):
u"""Application Root Resource
Since Traversal is not used, it is passed to View as context as it is.
"""
__name__ = None
__parent__ = None
__acl__ = []
def __init__(self, request):
self._repos = {
'user': UserRepository(),
}
@property
def repos(self):
u"""Each repository is provided via a dictionary"""
return self._repos
If you pass it to the root_factory argument in the application definition,
config = Configurator(
settings=settings,
root_factory="foo.resource.RootResource"
)
You can access repos from view as follows:
@view_config(route_name="user_detail")
def user_detail(context, request):
user_repo = context.repos['user']
user = user_repo.getById(...)
return ...
-Resources --The Pyramid Web Application Framework
Recommended Posts