Django--cookie&session

Source: Internet
Author: User

First, the basic

Cookies are saved locally in the browser format: iii= "8jblpb9g2l5c9xvofhv5pt8c0v967z5t"

Session is saved on the server side. Format: {"Cookie value": {"IsLogin": True, "username": "xxx"},cookie:{}}

Second, the process
    1. Server generates a string
    2. Sends a string to the client browser while placing the session information as a key
    3. Set any value in the value (dictionary) corresponding to the user's session
Third, error resolution errors:no such table:django_session

Reason:

The Django session is placed in the database, and the table is initialized first.

Solve:

Project directory path > Python manage.py migrate

Iv. Example 1, demand

The order page is not logged in and cannot be accessed directly to the login page.

2. Login Page app01/views.py
12345678 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‘)
urls.py
12345 fromapp01 import viewsurlpatterns =[    url(r‘^admin/‘, admin.site.urls),    url(r‘^login/$‘, views.login),]
Templates/login.html
1234567 <body>    <form action="/login/" method="post">        <input type="text" name="username">        <input type="password" name="pwd">        <input type="submit" value="submit">    </form></body>
4. Order Pageapp01/views.py

123456 def order(request):    is_login = request.session.get(‘is_login‘,False)    #False是默认值,不设置会报错    if is_login:        return HttpResponse(‘order‘)    else:        return redirect(‘/login/‘)
urls.py

123456 from app01 import views Code class= "Python plain" >urlpatterns = [      url (R ' ^admin/' , Admin.site.urls),      url (R ' ^order/$ '      Code class= "Python Plain" >url (R ' ^login/$ '
5. Browser


6. Database

7. Extension: The top right corner of the order page shows the logged in user

You can also define other values, such as username, which are set when the login is successful, and the page can display different data depending on the user.

views.py
123456789 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‘)
views.py
1234567 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/‘)
Oreder.html
123 <body>{{username}}</body>
8, write off? order.html
1234 <body>{{ username }}<ahref="/logout/">注销</a>    #加入注销跳转到logout函数处理</body>
urls.py
12345678 from app01 import viewsurlpatterns = [    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]
views.py

123 deflogout(request):    del request.session[‘is_login‘]    returnredirect(‘/login/‘)
V. Cookie time-out period settings.py
1 SESSION_COOKIE_AGE =5    #单位:秒
The session also has
12345 request.session.set_expiry(value)*如果value是个整数,session会在些秒数后失效。* 如果value是个datatime或timedelta,session就会在这个时间后失效。* 如果value是0,用户关闭浏览器session就会失效。*如果value是None,session会依赖全局session失效策略。
More

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

















From for notes (Wiz)

Django--cookie&session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.