zoukankan      html  css  js  c++  java
  • django视图函数中 应用装饰器

    from django.shortcuts import render, redirect, HttpResponse
    from .forms import LoginForm, RegistrationForm
    from django.contrib.auth import authenticate, login, logout
    from django.contrib.auth.models import User
    from django import forms
    from .models import UserInfo
    
    
    # 不带参数的装饰器
    def outer(func):
        def inner(request, *args, **kwargs):
            if request.user.is_authenticated:
                return func(request, *args, **kwargs)
            else:
                return redirect('/account/login/')
        return inner
    
    
    # 单参数的装饰器
    def outer_args(arg):
        def outers(func):
            def inner(request, *args, **kwargs):
                if request.user.is_authenticated:
                    return func(request, *args, **kwargs)
                else:
                    print(arg)
                    return redirect(arg)
            return inner
        return outers
    
    
    def user_login(request):
        if request.method == 'GET':
            form_obj = LoginForm()
            return render(request, 'account/login.html', {'form': form_obj})
    
        if request.method == 'POST':
            form_obj = LoginForm(request.POST)
            if form_obj.is_valid():
                user = authenticate(username=form_obj.cleaned_data['username'], password=form_obj.cleaned_data['password'])
                if user:
                    login(request, user)
                    return redirect('/')
                else:
                    return HttpResponse('username or password is not right !')
            else:
    
                return render(request, 'account/login.html', {'form': form_obj})
    
    
    def user_logout(request):
        logout(request)
        return redirect('/')
    
    
    def register(request):
        if request.method == 'GET':
            register_form = RegistrationForm()
            return render(request, 'account/register.html', {'form':register_form, 'user': None})
    
        if request.method == 'POST':
            register_form = RegistrationForm(request.POST)
            if register_form.is_valid():
                new_user = register_form.save(commit=False)
                new_user.set_password(register_form.cleaned_data['password'])
                new_user.save()
                return redirect('/')
            else:
                return render(request, 'account/register.html', {'form': register_form, 'user': None})
    
    
    @outer_args('/account/login/')
    def personal_data(request):
        return HttpResponse('OK')
    

      

  • 相关阅读:
    20170612测试
    vijos1453曼哈顿距离
    vijos1153 猫狗大战
    vijos1037搭建双塔
    dijkstra+priority_queue+vector
    BZOJ1507: [NOI2003]Editor
    dinic模板
    旅行-树形DP
    51nod1799-二分答案
    51nod1791-合法括号子段
  • 原文地址:https://www.cnblogs.com/liyqiang/p/8744581.html
Copyright © 2011-2022 走看看