Skip to content

Instantly share code, notes, and snippets.

@hadrien
Last active November 4, 2019 22:39
Show Gist options
  • Save hadrien/8658263 to your computer and use it in GitHub Desktop.
Save hadrien/8658263 to your computer and use it in GitHub Desktop.
Pyramid: Quick traversal example
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))
@merwok
Copy link

merwok commented Nov 4, 2019

This still works ✨

Two changes needed: Root class must be defined after the classes referenced in children dict, and needs an init method with signature __init__(self, request).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment