Could someone开发者_C百科 show me how i could write a login decorator like @redirect_to_home
for my views so that it modifies the request.PATH
variable to a new a value like /
whenever it is applied to a view.
I've seen people do quite complex stuff with decorators: I'm yet to figure them out thoroughly.
Thanks
The best way to start is to understand the login decorator from the django project ( auth module ): http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33
If you look at the "user_passes_test" function you'll see how to access request object.
A good tutorial about decorators : http://www.ibm.com/developerworks/linux/library/l-cpdecor.html For some examples of useful decorators see : http://wiki.python.org/moin/PythonDecoratorLibrary
Thanks to Piotr for his helpful examples.
def fake_requested_from_root(fn):
"""
Login decorator which when used on a view modifies the reqquest.path
to fool the template into thibking that the request is coming from the
root page
"""
def decorator(request, **kwargs):
request.path = reverse('home')
return fn(request, **kwargs)
return decorator
精彩评论