1.URLS
urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘,views.index), url(r‘^login/‘,views.login), url(r‘^test/‘,views.test),] 2.Views 代码
from django.shortcuts import render,redirect,HttpResponse # Create your views here.‘‘‘def login(request): if request.method == ‘POST‘: username=request.POST[‘user‘] password=request.POST[‘pwd‘] if username ==‘Freeman‘ and password == ‘redhat‘: request.session[‘login‘] =True return redirect(‘/index/‘) else: return render(request,‘login.html‘) else: return render(request,‘login.html‘)def index(request): is_login = request.session.get(‘login‘,False) if is_login: return HttpResponse(‘Say hi here is index‘) else: return redirect(‘/login/‘) #return render(request,‘index.html‘)def logout(request): del request.session[‘login‘] return redirect(‘login‘)‘‘‘def outer(func): print (‘start --------------------------------‘) def wrap(request,*arg,**kwargs): is_login=request.session.get(‘login‘,None) if is_login: ret = func(request,*arg,**kwargs) return ret else: return redirect(‘/login/‘) return wrap@outerdef index(request): return HttpResponse(‘index‘) def login(request): if request.method == ‘POST‘: username=request.POST[‘user‘] password=request.POST[‘pwd‘] if username ==‘Freeman‘ and password == ‘redhat‘: request.session[‘login‘] =True return redirect(‘/index/‘) else: return render(request,‘login.html‘) else: return render(request,‘login.html‘) @outerdef test(request): return HttpResponse(‘test‘) ###########################################################################################################################3通过以上代码,我们可能使用sessions和cookies 做页面的验证,比如要想访问某个页面必须经过LOGIN验证,而且经过验证的可以下次访问的时候不用再验证了。
时间: 2024-10-29 05:00:21