如何在Pyramid Framework中正确配置路由?

时间:2016-07-03 17:07:12

标签: pyramid

我想注册请求处理程序,但不想使用扫描方法。

为什么我需要调用两个方法(add_route和add_view)而不是一个?

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config


@view_config(name='home')
def home(request):
    return Response('Welcome!')


def add_view(config, handler, name, path):
    config.add_route(name, path)
    config.add_view(handler, name=name)


if __name__ == '__main__':
    config = Configurator()
    add_view(config, home, 'home', '/')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

1 个答案:

答案 0 :(得分:5)

(1)如果在Pyramid中使用@view_config装饰器,则必须使用config.scan()。 (这是声明性配置。)请参阅Adding View Configuration Using the @view_config Decorator

或者,您可以使用config.add_view()使用命令式配置。请参阅Adding View Configuration Using add_view()

(2)也许你应该问,“为什么我要用一个声明配置我的路线和视图?”这样做可以防止您为单个路径分配多个视图。保存一行代码的便利性有其缺点。

在金字塔中,单独声明路径和视图允许您为单个路径分配许多视图。例如,为同一路由为GET请求分配一个视图,为POST请求分配另一个视图。作为一方的好处,它使创建RESTful API变得更加繁琐。有关更多信息,请参阅Pyramid文档Pyramid Introduction - View predicates and many views per route