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

时间:2022-09-23 01:06:09

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.

这项任务似乎微不足道,但我无法找到解决方案。我会非常感谢任何帮助。

4 个解决方案

#1


6  

Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.

查看django.contrib.auth装饰器的源代码。它们完全符合您的要求,但对于内置的Django身份验证系统(请参阅文档)。为您的身份验证系统做类似的事情应该不难。

BTW, why don't you use the built-in auth? You can use it with custom authentication backends...

顺便说一句,你为什么不使用内置的auth?您可以将它与自定义身份验证后端一起使用...

#2


2  

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,谢谢你的帮助。

#3


1  

Function decorators comes to mind

想到函数装饰器

#4


0  

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!

在页面上还有一个特殊身份验证模板的示例,您可以根据自己喜欢的方式设置样式!

#1


6  

Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.

查看django.contrib.auth装饰器的源代码。它们完全符合您的要求,但对于内置的Django身份验证系统(请参阅文档)。为您的身份验证系统做类似的事情应该不难。

BTW, why don't you use the built-in auth? You can use it with custom authentication backends...

顺便说一句,你为什么不使用内置的auth?您可以将它与自定义身份验证后端一起使用...

#2


2  

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,谢谢你的帮助。

#3


1  

Function decorators comes to mind

想到函数装饰器

#4


0  

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!

在页面上还有一个特殊身份验证模板的示例,您可以根据自己喜欢的方式设置样式!