开发者

How to specify that login is required somewhere other than a view in Django?

So I have an app called stats that lets me query my database in various ways and return information in a JSON format so I can have a nice ajaxy dashboard for graphing and visualizing. I'd like this app to be as reusable as possible, naturally, so I don't want to necesarily use the @login_required decorator on its views. In my case, however, I do want a login to be required befo开发者_如何学运维re viewing any of the apps views. Is there a way to do this somewhere other than the views?

Perhaps something like this in my site's urls.py? (I know this won't work, an example of what I'm looking for)

urlpatterns = patterns('',
        (r'^stat/', include('stats.urls'), login_required), 
)


You can apply decorator for individual urls in urls.py in this manner:

from django.contrib.auth.decorators import login_required
import views

(r'^stat/', login_required(views.index))


you can use a middleware for that

here is example snippet - http://www.djangosnippets.org/snippets/1179/

you can use this snippet and define LOGIN_EXEMPT_URLS in your settings or modifiy it a little bit for your case


If you're concerned about reusability, rather than using login_required, you could use a decorator which requires login if a particular argument is passed to the view (which might default to a value of True). Off the top of my head, it might look a little like this:

from django.contrib.auth.decorators import login_required

def login_possibly_required(view_func):
    def inner(request, *args, **kwargs):
        try:
            require_login = kwargs.pop('require_login')
            if require_login:
                return login_required(view_func)(request, *args, **kwargs)
        except KeyError:
            pass
        return view_func(request, *args, **kwargs)
    return inner

Then you'd define your views like so:

@login_possibly_required
my_view(request, arg1, arg2, require_login=True):
    pass

Not tested, but you get the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜