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')