Route and View Examples

这里是最常见的路线和视图。

  1. Fixed controller and action.

    1# Pylons
    2map.connect("faq", "/help/faq", controller="help", action="faq")
    3class HelpController(Base):
    4    def faq(self):
    5        ...
    
    1# Pyramid
    2config.add_route("faq", "/help/faq")
    3@view_config(route_name="faq", renderer="...")
    4def faq(self):   # In some arbitrary class.
    5    ...
    

    .

  2. 固定的控制器和动作,以及其他路由变量。

    1# Pylons
    2map.connect("article", "/article/{id}", controller="foo",
    3    action="article")
    4class FooController(Base):
    5    def article(self, id):
    6        ...
    
    1# Pyramid
    2config.add_route("article", "/article/{id}")
    3@view_config(route_name="article")
    4def article(self):   # In some arbitrary class.
    5    id = self.request.matchdict["id"]
    

    .

  3. Variable controller and action.

    # Pylons
    map.connect("/{controller}/{action}")
    map.connect("/{controller/{action}/{id}")
    
    # Pyramid
    # Not possible.
    

    不能通过Pyramid中的路由变量选择视图类。

  4. Fixed controller, variable action.

    # Pylons
    map.connect("help", "/help/{action}", controller="help")
    
    1# Pyramid
    2config.add_route("help", "/help/{action}")
    3
    4@view_config(route_name="help", match_param="action=help", ...)
    5def help(self):   # In some arbitrary class.
    6    ...
    

    “pyramid-handlers”包提供了一种替代方法。

Other Pyramid examples:

1# Home route.
2config.add_route("home", "/")
3
4# Multi-action route, excluding certain static URLs.
5config.add_route("main", "/{action}",
6    path_info=r"/(?!favicon\.ico|robots\.txt|w3c)")

pyramid_handlers

“ Pyramid 处理程序”是一个附加包,它提供了一种可能更方便的方法来处理上面的case 4,一个带有命名视图的“action”变量的路由。它的工作原理如下:

 1# In the top-level __init__.py
 2from .handlers import Hello
 3def main(global_config, **settings):
 4    ...
 5    config.include("pyramid_handlers")
 6    config.add_handler("hello", "/hello/{action}", handler=Hello) 
 7
 8# In zzz/handlers.py
 9from pyramid_handlers import action
10class Hello(object):
11    __autoexpose__ = None
12
13    def __init__(self, request):
14        self.request = request
15
16    @action
17    def index(self):
18        return Response('Hello world!')
19
20    @action(renderer="mytemplate.mak")
21    def bye(self):
22        return {}

这个 add_handler @action

这个 __autoexpose__ class attribute (line 11) can be a regex. If any method name matches it, it will be registered as a view even if it doesn't have an @action

注意 @action 装饰师是 not 被认可 config.scan() config.add_hander .

@view_config because it's "standard Pyramid".

资源路由

“ Pyramid 路由器助手”提供 config.add_resource 行为类似于 Pylons 的方法 map.resource . 它以一种宁静的方式(遵循Atom发布协议)添加一组路由到列表/查看/添加/修改/删除资源。有关详细信息,请参阅链接中的源文档字符串。

注意:这里的“资源”一词是 not 与遍历资源相关。