金字塔装饰器链接

Pyramid decorator chaining

在我的金字塔应用程序中,我试图通过装饰视图函数来实现授权。
当我使用 config.scan() 函数时,视图的 none 被添加,但是如果我使用 config.add_view() 明确添加它们,一切正常。

我有两个文件,其中一个定义了所有视图函数 (views.py)

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

from functools import wraps

def authorized(func):    #decorator difnition
    @wraps(func)
    def new_func(request):
        if(request.cookies.get('user')):   # authorization
            return func(request)
        else:
            return Response('not authirised')
    return new_func



@view_config(route_name='hello')           # view function being decorated
@authorized
def privileged_action(request):
    return Response('Hello %(name)s!' % request.matchdict)

和另一个文件来创建导入 views.py

的服务器 (serve.py)
from wsgiref.simple_server import make_server
from pyramid.config import Configurator

from views import privileged_action

if __name__ == '__main__':
    config = Configurator()
    config.add_route('hello', '/hello/{name}')
    # config.add_view(privileged_action, route_name='hello')   # This works
    config.scan()                                              # This doesn't work
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

如果我使用“http://localhost:8080/hello/a
访问,这会出现 404 未找到错误 为什么这不起作用?
有什么办法可以做到这一点吗?

你的装饰器代码看起来不错。

Configurator.scan() 的文档指出其第一个参数:

The package argument should be a Python package or module object (or a dotted Python name which refers to such a package or module). If package is None, the package of the caller is used.

因此请确保您正在做config.scan(views),让您的网络应用程序动态添加您的视图。