python - Pyramid 装饰器链接

标签 python pyramid

在我的 Pyramid 应用程序中,我试图通过装饰 View 函数来实现授权。
当我使用 config.scan() 函数时,没有添加任何 View ,但是如果我使用 config.add_view() 显式添加它们,一切正常。

我有两个文件,其中一个定义了所有 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 not found 错误'
为什么这不起作用?
有什么方法可以使它起作用吗?

最佳答案

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

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),以使您的网络应用程序动态添加您的 View 。

关于python - Pyramid 装饰器链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34559179/

相关文章:

python - 删除具有只读权限的文件,但对父文件夹具有写入权限

python - 如何在 Pyramid 中全局重定向 IP 地址?

python - 如何在不安装的情况下使用 pserve 部署 Pyramid 应用程序?

python - Pyramid Web 应用程序中的 Rabbitmq 连接管理?

python - 如何将列表列表转换为字节?

python - 通过 os.system 推送

python - flake8:仅忽略整个文件中的 F401 规则

Python 字典和线程并发

python - Pyramid 遍历HTTP PUT到不存在的URI

angular - 如何在 Pyramid Web View 中创建/设置 Angular 2 应用程序