Pyramid decorator chaining

In my pyramid application I am trying to implement authorization by decorating the view function.
When I use the config.scan() function none of the views are added, however if I explicitly add them using config.add_view() everything works fine.

I have two file one which defines all the view functions (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)

And another file to create the server (serve.py) which imports views.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()

This gives 404 not found error if I access using 'http://localhost:8080/hello/a'
Why does this not work?
Is there any way to make this work?


Your code with the decorators looks fine.

The documentation for Configurator.scan() states for its first argument:

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.

So make sure you are doing config.scan(views) , to get your web app dynamically adding your views.

链接地址: http://www.djcxy.com/p/69096.html

上一篇: 从另一个应用程序中调用金字塔框架应用程序

下一篇: 金字塔装饰者链接