In Pyramid using crawl, how to create dynamic urls?

I am new to Pyramid and created the application. I have a database with a category table. A category can be colors with attributes Red and Green, and another category can be the size of attributes 4 and 5. I would like to be able to create links such as: domain.com/{category}. So, let's say I have two categories of templates. One is color.mak and one is size.mak. How can I get it so that domain.com/Red or domain.com/Green display color.mak and domain.com/4 or domain.com/5 display size.mak? After reading the differences between the URL manager and Traversal, it looks like Traversal will be preferable to what I want, even if it can be done anyway. I am really stuck on how to add these categories to the resource tree.

+4
source share
1 answer

First, you want your Root resource to return different types of resources 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 want to configure different views for different types of resources (aka 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 specific URL, Traversal will look for a specific context and view name. For domain.com/Red, the context will be ColorCategory('Red') (because it returns the Root resource), and the view name will be '' (because the path is completely absorbed after searching for this context). Then the pyramid will use the context type and view name as filters to search for the customized view and template.

+6
source

All Articles