为什么根路径没有路由到我的视图?

时间:2018-04-14 13:25:09

标签: python python-3.x pyramid

如何将根路径(即/)路由到视图?这是我的简单设置:

import sys
import wsgiref.simple_server

from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

def main(argv):
    # Create Application.
    with Configurator() as config:
        app = config.make_wsgi_app()

    # Serve HTTP requests.
    server = wsgiref.simple_server.make_server('localhost', 8080, app)
    server.serve_forever()
    return 0

@view_config(name='')
def page(request):
    return Response("Root")

if __name__ == '__main__':
    sys.exit(main(sys.argv))

当我请求http://localhost:8080/时,我只是得到了404响应。从日志中:

127.0.0.1 - - [14/Apr/2018 09:14:50] "GET / HTTP/1.1" 404 153

回复机构:

<html>
 <head>
  <title>404 Not Found</title>
 </head>
 <body>
  <h1>404 Not Found</h1>
  The resource could not be found.<br/><br/>
 </body>
</html>

我正在运行Python 3.5和Pyramid 1.9.1。

1 个答案:

答案 0 :(得分:1)

您似乎忘记调用config.scan(),这会添加您使用@view_config注释的路线:

import sys
import wsgiref.simple_server

from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

def main(argv):
    # Create Application.
    with Configurator() as config:
        config.scan()  # adds routes configured with the decorator
        app = config.make_wsgi_app()

    # Serve HTTP requests.
    server = wsgiref.simple_server.make_server('localhost', 8080, app)
    server.serve_forever()
    return 0

@view_config(name='')
def page(request):
    return Response("Root")


if __name__ == '__main__':
    sys.exit(main(sys.argv))

根据docs

  

仅仅存在@view_config装饰器不足以执行视图配置。装饰器所做的就是使用您的配置声明“注释”该函数,它不处理它们。要使Pyramid处理pyramid.view.view_config声明,必须使用pyramid.config.Configurator的扫描方法