在我的 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/