【问题标题】:Pyramid routing issue金字塔路由问题
【发布时间】:2014-01-18 07:00:01
【问题描述】:

我正在尝试使用动态路由设置 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()

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

    在你的 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(),然后它会查找所有 @view_config 声明,其 route_name 与配置的路由之一匹配:

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

    将检测到:

    @view_config(route_name="foo")
    

    此外,如果您要将 run_action 作为独立函数(而不是类方法),它应该接受一个参数,“请求”(而不是摘录中的“自我”):

    @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}
    

    【讨论】:

    • 这与 OP 的问题没有直接关系,所以我将其作为评论留下。我在 Pyramid 应用程序中遇到了 404 问题。 config.scan 调用和 @view_config 装饰器都已就位。我的问题是,显然,我有两个具有不同 @view_config 装饰的同名方法。
    【解决方案2】:

    金字塔文档: 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
    

    _ 初始化_.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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2012-05-09
      • 2013-07-14
      • 1970-01-01
      相关资源
      最近更新 更多