标签:
cookie保存在浏览器本地,格式:iii="8jblpb9g2l5c9xvofhv5pt8c0v967z5t"
session保存在服务器端。格式:{"cookie值":{"isLogin":True,"username":"xxx"},cookie:{}}
Django的session是放在数据库里,要先初始化表。
项目目录路径> python manage.py migrate
订单页面未登录不能访问,直接跳转到登录页面。
1 2 3 4 5 6 7 8 | def login(request): if request.method = = ‘POST‘ : username = request.POST.get( ‘username‘ ) pwd = request.POST.get( ‘pwd‘ ) if username = = ‘user1‘ and pwd = = ‘123‘ : request.session[ ‘is_login‘ ] = True return redirect( ‘/order/‘ ) return render(request, ‘login.html‘ ) |
1 2 3 4 5 | from app01 import views urlpatterns = [ url(r ‘^admin/‘ , admin.site.urls), url(r ‘^login/$‘ , views.login), ] |
1 2 3 4 5 6 7 | < body > < form action = "/login/" method = "post" > < input type = "text" name = "username" > < input type = "password" name = "pwd" > < input type = "submit" value = "submit" > </ form > </ body > |
1 2 3 4 5 6 | def order(request): is_login = request.session.get( ‘is_login‘ , False ) #False是默认值,不设置会报错 if is_login: return HttpResponse( ‘order‘ ) else : return redirect( ‘/login/‘ ) |
1 2 3 4 5 6 | from app01 import views urlpatterns = [ url(r ‘^admin/‘ , admin.site.urls), url(r ‘^order/$‘ , views.order), url(r ‘^login/$‘ , views.login), ] |
还可以定义其它值,如username,登录成功的时候就设置上,然后页面可以根据不同的用户显示不同的数据。
1 2 3 4 5 6 7 8 9 | def login(request): if request.method = = ‘POST‘ : username = request.POST.get( ‘username‘ ) pwd = request.POST.get( ‘pwd‘ ) if username = = ‘user1‘ and pwd = = ‘123‘ : request.session[ ‘is_login‘ ] = True request.session[ ‘username‘ ] = ‘user1‘ return redirect( ‘/order/‘ ) return render(request, ‘login.html‘ ) |
1 2 3 4 5 6 7 | def order(request): is_login = request.session.get( ‘is_login‘ , False ) #False是默认值,不设置会报错 if is_login: username = request.session.get( ‘username‘ , False ) return render(request, ‘order.html‘ ,{ ‘username‘ :username}) else : return redirect( ‘/login/‘ ) |
1 2 3 | < body > {{username}} </ body > |
1 2 3 4 | < body > {{ username }} < a href = "/logout/" >注销</ a > #加入注销跳转到logout函数处理 </ body > |
1 2 3 4 5 6 7 8 | from app01 import views urlpatterns = [ url(r ‘^admin/‘ , admin.site.urls), url(r ‘^$‘ , views.index), url(r ‘^order/$‘ , views.order), url(r ‘^login/$‘ , views.login), url(r ‘^logout/$‘ , views.logout), #加一个logout ] |
1 2 3 | def logout(request): del request.session[ ‘is_login‘ ] return redirect( ‘/login/‘ ) |
1 | SESSION_COOKIE_AGE = 5 #单位:秒 |
1 2 3 4 5 | request.session.set_expiry(value) * 如果value是个整数,session会在些秒数后失效。 * 如果value是个datatime或timedelta,session就会在这个时间后失效。 * 如果value是 0 ,用户关闭浏览器session就会失效。 * 如果value是 None ,session会依赖全局session失效策略。 |
https://docs.djangoproject.com/en/1.9/topics/http/sessions/
http://docs.30c.org/djangobook2/chapter14/
https://docs.djangoproject.com/en/1.9/ref/settings/#settings-sessions
标签:
原文地址:http://www.cnblogs.com/daliangtou/p/5284448.html