将多个函数转换为类方法

35 阅读2分钟

我有一些函数需要有'重定向'过滤器。这个过滤器的工作原理大致如下 --

  1. 如果用户未登录且没有会话数据,则重定向到登录页面。
  2. 如果用户已登录并已填写页面,则重定向到用户主页。
  3. 如果用户已登录但尚未填写页面,请留在页面上。
  4. 如果用户未登录但有会话数据,请留在页面上。 我已经开始将函数转换为基于类的实现方式,以便提高效率并减少代码(以前我的视图函数非常庞大)。这是我第一次尝试实现基于类的功能,这是我目前为止所做的--
def redirect_filter(request):
    if request.user.is_authenticated():
        user = User.objects.get(email=request.user.username)
        if user.get_profile().getting_started_boolean:
            return redirect('/home/') ## redirect to home if a logged-in user with profile filled out
        else:
            pass  ## otherwise, stay on the current page
    else
        username = request.session.get('username')
        if not username:  ## if not logged in, no session info, redirect to user login
            return redirect('/account/login')
        else:
            pass  ## otherwise, stay on the current page

def getting_started_info(request, positions=[]):
    location = request.session.get('location')
    redirect_filter(request)
    if request.method == 'POST':
        form = GettingStartedForm(request.POST)
        ...(run the function)...
    else:
        form = GettingStartedForm() # inital = {'location': location}
    return render_to_response('registration/getting_started_info1.html', {'form':form, 'positions': positions,}, context_instance=RequestContext(request))

显然,这个视图还没有完全正常工作。我该如何将其转换为可用的功能? 此外,我还有三个变量需要在几个getting_started函数中重复使用:

user = User.objects.get(email=request.user.username)
profile = UserProfile.objects.get(user=user)
location = profile.location

我应该将这些变量定义放在哪里才能在所有函数中重复使用它们,我该如何调用它们? 感谢。

2、解决方案 Django 实际上已经包含了一个login_required装饰器,它可以轻松地处理用户认证。只需在view.py页面的顶部包含以下代码:

from django.contrib.auth.decorators import login_required

然后在任何需要登录的视图之前添加

@login_required 

它甚至会在用户登录后将用户重定向到相应的页面。 更多信息请查看: docs.djangoproject.com/en/dev/topi… 这会极大地简化你的视图,并可能不必编写一个单独的类,因为剩下的只是一个简单的重定向。 至于变量,每个请求都包含一个带有用户信息的request.user对象。你可以在文档中搜索请求和响应对象以了解更多信息。 你可以使用user对象通过扩展用户模块来获取profile变量。在设置中设置AUTH_PROFILE_MODULE = 'myapp.UserProfile',这将允许你以如下方式访问用户个人资料:

user.get_profile().location. 

更多信息请查看: www.b-list.org/weblog/2006…