擅长:python、mysql、java
<p>玩了上面的各种链接,却无法让他们工作,然后遇到了这个非常简单的我适应了。<a href="http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/" rel="noreferrer">http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/</a></p>
<pre><code>from functools import wraps
from django.http import HttpResponseRedirect
def authors_only(function):
@wraps(function)
def wrap(request, *args, **kwargs):
profile = request.user.get_profile()
if profile.usertype == 'Author':
return function(request, *args, **kwargs)
else:
return HttpResponseRedirect('/')
return wrap
</code></pre>
<hr/>
<p><em>使用<code>@wraps</code>比像使用<code>wrap.__doc__ = fn.__doc__</code>那样手动重写要好。除此之外,它还确保包装函数与包装函数的名称相同。</em></p>
<p>见<a href="https://docs.python.org/2/library/functools.html" rel="noreferrer">https://docs.python.org/2/library/functools.html</a></p>