Last active
November 4, 2019 22:39
-
-
Save hadrien/8658263 to your computer and use it in GitHub Desktop.
Pyramid: Quick traversal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyramid.httpexceptions import HTTPCreated, HTTPBadRequest | |
from pyramid.views import view_config | |
def includeme(config): | |
config.set_root_factory(Root) | |
config.scan() | |
class Root(object): | |
children = { | |
'tags': TagsCollection, | |
} | |
def __getitem__(self, key): | |
self.children[key](key, self) | |
class TagsCollection(object): | |
def __init__(self, name, parent): | |
self.__name__ = name | |
self.__parent__ = parent | |
def create(self, params): | |
try: | |
name = params['tag_name'] | |
except KeyError: | |
raise HTTPBadRequest('missing tag_name param') | |
new_resource = TagResource(name, self) | |
new_resource.create(params) | |
return new_resource | |
def __getitem__(self, name): | |
return TagResource(name, self) | |
class TagResource(object): | |
def __init__(self, name, parent): | |
self.__name__ = name | |
self.__parent__ = parent | |
def create(self, params): | |
# call model to create tag on db | |
db.create_tag(self.__name__, params) | |
return self | |
@view_config(context=TagsCollection, request_method='POST', renderer='json') | |
@view_config(context=TagResource, request_method='PUT', renderer='json') | |
def create_tag(context, request): | |
new_resource = context.create(request.params) | |
return HTTPCreated(location=request.resource_url(new_resource)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This still works ✨
Two changes needed:
Root
class must be defined after the classes referenced inchildren
dict, and needs an init method with signature__init__(self, request)
.