开发者

In Pyramid, using traversal, how do create dynamic urls?

I am new to Pyramid and have created an application. I have a database with a table of categories. A category might be color with the attributes Red and Green, and another category might be size with the attributes 4 and 5. I'd like to be able to create links that are like: domain.com/{category}. So let's say I have two category templates. One is color.mak and one is size.mak. How would I get it so domain.com/Red or domain.com/Green would render color.mak and domain.com/4 or domain.com/5 would render size.mak? After reading the differences between URL Dispatch and Traversal, it seems like Traversal would be preferred for what I want even though it could be done either way. What I'm really stuck on is how to add these categories to my resource t开发者_JAVA技巧ree.


First, you'll want your Root resource to return different resource types from __getitem__:

class Root(object):
    def __getitem__(self, key):
        if key in ['Red', 'Green']:
            return ColorCategory(key)
        elif key in ['4', '5']:
            return SizeCategory(key)

class ColorCategory(object):
    ...

class SizeCategory(object):
    ...

Then in your __init__.py, you'll want to configure different views for your different resource types (a.k.a. context types):

    config.add_view('myapp.views.color',
                context='myapp:resources.ColorCategory', name='',
                renderer='myapp:templates/color.mak')

    config.add_view('myapp.views.size',
                context='myapp:resources.SizeCategory', name='',
                renderer='myapp:templates/size.mak')

The way this will work is that when you get a certain URL, Traversal will look up a certain context and view name. For domain.com/Red, the context will be ColorCategory('Red') (because that's what your Root resource returns) and the view name will be '' (because the path is totally consumed after looking up that context). Then pyramid will use the context type and view name as filters to find a configured view and template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜