2014-01-17 73 views
1

我试图建立一个JSON的服务与动态路由:/动作/ {ID}金字塔路由问题

我收到了404,当我浏览到:http://example.com:8080/action/test

基于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() 

回答

3

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

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

的@view_config装饰并没有做自己的事情。你必须调用config.scan(),然后会去寻找那些有ROUTE_NAME匹配配置的途径之一所有@view_config声明:

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} 

如果你这样做计划跑步_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} 
+0

它与OP的问题没有直接关系,所以我只是将其作为评论。我在金字塔应用程序中遇到了404个问题。 'config.scan'调用和'@ view_config'装饰器都已就位。我的问题显然是,我有两个具有不同'@ view_config'装饰的名称相同的方法。 – skytreader

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()