简体   繁体   English

如何在django的每个视图中运行一段代码?

[英]How to run a piece of code in every view in django?

I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed. 如果授权失败,我需要在我的一个Django应用程序的每个视图中检查用户授权(我不使用Django内置的auth系统)并将用户重定向到“login please”页面。

Code looks like this: 代码如下所示:

try:
    admin_from_session = request.session['admin'];
    admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
    return HttpResponseRedirect('/controlpanel/login')

Question is: how can I run this code at the beginning of every view, without repeating it every time? 问题是: 如何在每个视图的开头运行此代码,而不是每次都重复?

If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization: 如果我在PHP上编写我的程序,我会将这些代码放在单独的文件中,并在需要授权的每个页面的开头写下这样的代码:

include("redirect_if_not_logged_in.inc.php");

The solutions I found was: 我找到的解决方案是:

  • inclusion tags - doesn't do, because I can't redirect anywhere from there 包含标签 - 没有,因为我无法从那里重定向
  • custom function - also doesn't do, because of the same reason. 自定义功能 - 也不做,因为同样的原因。

The task seems trivial, but I can't find a solution. 这项任务似乎微不足道,但我无法找到解决方案。 I would be very grateful for any help. 我会非常感谢任何帮助。

Look at the source code for django.contrib.auth decorators . 查看django.contrib.auth装饰器源代码 They do exactly what you want, but for the built-in Django authentication system ( see the documentation ). 它们完全符合您的要求,但对于内置的Django身份验证系统( 请参阅文档 )。 It shouldn't be hard to do something similar for your authentication system. 为您的身份验证系统做类似的事情应该不难。

BTW, why don't you use the built-in auth? 顺便说一下,你为什么不使用内置的auth? You can use it with custom authentication backends... 您可以将它与自定义身份验证后端一起使用...

I found the answer I was looking for. 我找到了我正在寻找的答案。 Function decorators allow to run a peace of code at the beginning of a function. 函数装饰器允许在函数开头运行代码。

You must define a decorator function 您必须定义装饰器功能

def login_please_decorator(view_func):
    """
        Redirect if admin was not logged in
    """
    def _decorated(request, *args, **kwargs):
        #Check authorization
        try:
            admin_from_session = request.session['admin'];
            admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
            return view_func(request,*args, **kwargs);
        except KeyError, Administrator.DoesNotExist:
            return HttpResponseRedirect('/cp/login?ret=' + request.path);

    return _decorated 

And decorate a view using this function name: 并使用此函数名称装饰视图:

@login_please_decorator
def some view(request):   
    # do something ...
    # ...

Ludwik Trammer, bugspy.net, thank you for your help. Ludwik Trammer,bugspy.net,谢谢你的帮助。

想到功能装饰器

Take a look at the User authentication page here http://docs.djangoproject.com/en/dev/topics/auth/ 请查看此处的用户身份验证页面http://docs.djangoproject.com/en/dev/topics/auth/

Read on to "The login_required decorator". 继续阅读“login_required decorator”。

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
   ...

You can setup where the user is to be redirected if not authenticated via the setting "settings.LOGIN_URL". 如果未通过设置“settings.LOGIN_URL”进行身份验证,您可以设置用户重定向的位置。

At the page there is also an example for a special authentication template you can style to anything you like! 在页面上还有一个特殊身份验证模板的示例,您可以根据自己喜欢的方式设置样式!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM