举个例子,
def get_booking(f=None): print "Calling get_booking Decorator" def wrapper(request, **kwargs): booking = _get_booking_from_session(request) if booking == None: # we don't have a booking in our session. return HttpRedirect('/') else: return f(request=request, booking=booking, **kwargs) return wrapper @get_booking def do_stuff(request, booking): # do stuff here
我遇到的问题是,甚至在我调用我正在装饰的函数之前,就会调用@get_booking装饰器.
开始输出:
Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator Calling get_booking Decorator [26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0 [26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300 [26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800 [26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492
我甚至没有调用此时装饰的函数.
我刚刚开始装饰,所以也许我错过了一些东西.有帮助吗?
我相信python装饰器只是语法糖.
@foo def bar (): pass
是一样的
def bar (): pass bar = foo(bar)
正如您所看到的,即使没有调用bar,也会调用foo.这就是你看到装饰器功能的输出的原因.对于应用装饰器的每个函数,您的输出应包含一行.