金字塔路由问题

时间:2014-01-17 22:20:56

标签: python pyramid

我正在尝试使用动态路由设置json服务:/ action / {id}

当我导航到http://example.com:8080/action/test

时,我得到了404

基于this documentation,似乎我的路由配置正确,但事实并非如此。

我在这里做错了什么?

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


@view_config(route_name="action", renderer="json")
def run_action(self):
    id = self.request.matchdict['id']
    return {'id': id}


def main():
    config = Configurator()
    config.add_route('action', '/action/{id}')
    app = config.make_wsgi_app()
    return app


if __name__ == '__main__':
    app = main()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

2 个答案:

答案 0 :(得分:3)

在main()函数中调用config.scan():

def main():
    config = Configurator()
    config.add_route('action', '/action/{id}')
    config.scan()
    app = config.make_wsgi_app()
    return app

@view_config装饰器本身不做任何事情。您必须调用config.scan(),然后查找所有具有与config的路由匹配的route_name的@view_config声明:

config.add_route('foo')
config.scan()

会检测到:

@view_config(route_name="foo")

另外,如果你要将run_action作为一个独立的函数(而不是类方法),它应该接受一个参数,'request'(而不是你的摘录中的'self'):

@view_config(route_name="action", renderer="json")
def run_action(request):
    id = request.matchdict['id']
    return {'id': id}

如果您计划将run_action作为类方法,则需要正确初始化该类,并仅修饰类方法:

class MyArbitraryClass():
    def __init__(self, request):
        self.request = request

    @view_config(route_name="action", renderer="json")
    def run_action(self):
        id = request.matchdict['id']
        return {'id': id}

答案 1 :(得分:0)

金字塔文档: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/project.html

views.py

from pyramid.view import view_config


@view_config(route_name="action", renderer="json")
def run_action(request):
    id = request.matchdict['id']
    return {'id': id}


def main():
    config = Configurator()
    config.add_route('action', '/action/{id}')
    app = config.make_wsgi_app()
    return app

_ init _。py

from pyramid.config import Configurator

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.add_route('action', '/action/{id}')
    config.scan()
    return config.make_wsgi_app()