Python Web framework "supplemental" Cookie and session (Django)

Source: Internet
Author: User
Tags button type sessions unique id website performance

I. Introduction of cookies and session

Cookies are not part of the HTTP protocol, and because the HTTP protocol is not able to maintain state, we need to "keep state" in reality, so cookies are born in such a scenario.

A cookie works by creating content from the server, saving it locally when the browser receives it, and automatically bringing a cookie when the browser accesses it, so that the server can tell who it is by the content of the cookie.

Although a cookie solves the "hold-state" requirement to some extent, the cookie itself supports a maximum of 4096 bytes, and the cookie itself is stored on the client, which may be intercepted or stolen, so there is a need for something new, it can support more bytes, and he saves it in the server, Has a high level of security. This is the session.

The problem is that, based on the stateless features of the HTTP protocol, the server simply does not know who the visitor is. Then the above cookie acts as a bridge.

We can assign a unique ID to each client's cookie so that when the user accesses the cookie, the server knows who the person is. We then keep the private information on the server for a period of time, such as "account password" and so on, based on the ID of the different cookie.

In summary: Cookies compensate for the lack of HTTP stateless, let the server know who the person is "who", but the cookie in the form of text stored locally, its own security is poor; so we use cookies to identify different users, corresponding to the session to save private information and more than 4096 bytes of text.

In addition, the above mentioned cookie and session is actually a common thing, not limited to language and framework

Second, the application principle of login

In the previous sections we have been able to create a landing page, after verifying the correctness of the user name and password to jump to the background page. But the test also found that if the landing page is bypassed. Direct input to the background of the URL address can also be directly accessed. This is obviously unreasonable. What we are missing is the validation of cookies and session mates. With this verification process, we can implement the same as other sites must log in to enter the background page.

Let's start with this certification mechanism. Whenever we use a browser to access a landing page, once we pass the certification. The server side sends a random set of unique strings (assuming 123ABC) to the browser side, which is stored on the browsing side of what is called a cookie. The server side will also store the user's current state, such as Login=true,username=hahaha user information. But the store is stored in a dictionary, and the only key to the dictionary is the only cookie value that has just been sent to the user. So if you look at the session information on the server side, you'll theoretically see a dictionary like this

{' 123abc ': {' login ': true, ' Username:hahaha '}}

Because each cookie is unique, we also need to verify that we have to change the browser on the computer and then log on to the same website. So why do we just see this dictionary in theory? Because in the security considerations, in fact, the above large dictionary is not only the key value 123ABC is encrypted, value {' Login ': true, ' Username:hahaha ' is also encrypted on the server side. So, even if we open the session information on the server, we see something similar to the following.

{' 123abc ':d asdasdasd1231231da1231231}

Third, the simple use of cookies

1. Obtaining Cookies
Request. Cookies.get ("IsLogin", none)  #如果有就获取, no default is None
2. Set Cookies
  obj = Redirect ("/index/")  Obj.set_cookie ("IsLogin", True)  #设置cookie值, note the arguments here, one is the key, the other is the value  Obj.set_cookie ("Haiyan", "344",)  #20代表过期时间  Obj.set_cookie ("username", username)
3. Delete Cookies
Obj.delete_cookie ("Cookie_key", path= "/", Domain=name)

Login Authentication Example:

Need to know what time

A total of three requests
Note: The action walk path of form form is still/login/
First time request: Url:http://127.0.0.1:8080/login GET request
First request: Url:http://127.0.0.1:8080/login POST request user PASW
First request: The Url:http://127.0.0.1:8080/index POST request carries a cookie
Therefore, the cookie is taken on the index page because there is already a cookie in index

urls.py

From app01 import viewsurlpatterns = [    url (R ' ^admin/', admin.site.urls),    url (r ' ^login/', views.login),    URL (r ' ^index/', Views.index),]

  

views.py

From django.shortcuts import render,redirect,httpresponsefrom app01 import models# Create your views here.def login (reque ST): If request.method== "POST": Print ("All requests data", request.) POST) Username = Request. Post.get ("username") Password = Request. Post.get ("password") # View the user name and password in the database, compared to whether the user entered the value in the database ret = models. UserInfo.objects.filter (Username=username,password=password) if RET: #如果用户名和密码都正确, the login succeeded print (request.c ookies) #{' csrftoken ': ' 1eatcdqlxdwtr0exu4udqehelepoldrjosad7tfa7cbdxayxadvpbikazk6j0dvb '} # because the HTTP protocol is stateless, you Log in and don't know who is logged in, when others know your homepage URL, you can log in. So there's no privacy. # that's a cookie. obj = Redirect ("/index/") Obj.set_cookie ("IsLogin", True) #设置cook IE value, note here the parameters, one is the key, one is the value of Obj.set_cookie ("Haiyan", "344", "a") #20代表过期时间 Obj.set_cookie ("username", Userna Me) return obj Else:return render (Request, "login.html") Else:return render (reques T, "login.hTml ") def index (request): Is_login = Request. Cookies.get ("IsLogin", none) #得到cookie, have to get, do not get none if Is_login:username = Request.  Cookies.get ("username") print (username) return render (Request, "index.html", {"username": username}) Else: #如果没有拿到值, have been on the login page will not go to return redirect ("/login/")

  

models.py

Class UserInfo (models. Model):    username =models. Charfield (max_length=32)    password =models. Charfield (MAX_LENGTH=32)

  

Login.html

<! DOCTYPE html>

  

Index.html

<! DOCTYPE html>

  

Cookies are stored to the client

Advantage: The data is stored on the client. Reduce stress on the service side and improve website performance

Cons: Security is not high, the client can easily be viewed or cracked user session information

Iv. simple use of the session

1, basic operation (need to master)

1, set session value request.session["Session_name"]= "admin" 2, get session value Session_name = request.session ("Session_name") 3, Delete Session value del request.session["Session_name"]  delete a set of key values to Request.session.flush ()   Delete a record 4, detect whether the session value if "Session_name" is  request.session:

Other operations

5, Get (key, default=none) Fav_color = Request.session.get (' Fav_color ', ' Red ') 6, pop (key) Fav_color = Request.session.pop (' Fav_color ') 7, keys () 8, items () 9, SetDefault () 10, flush () deletes the current session data and deletes the session's cookie.            this is used to ensure that the previous session data cannot be accessed again by the user's browser            , for example, it is called in the Django.contrib.auth.logout () function.  11 Random string of user session        Request.session.session_key          # Delete        all data with session expiration date less than current date Request.session.clear_expired ()          # Check if the random string of the user session is request.session.exists in the database        ("Session_key")          # Delete all session data for the current user        request.session.delete ("Session_key")          Request.session.set_expiry (value)            * If value is an integer, the session will expire after a few seconds.            * If value is a datatime or timedelta,session, it will expire after this time.            * If value is 0, the user closes the browser session will expire.            * If value is none,session, it will depend on the global session expiration policy.

2. Process Analysis Diagram

Because the cookie will keep all the information in the client, that is, the browser, this will lead to unsafe, so the reference to the session, but only the session is not a good use, must session and cookie with this to use.

The session will store the information on the server side.

Session Principle Analysis Flow:

{"SessionID": "DFHASDJFHKJLCN4352KJDSFHKJSD"}

If post:

request.session["Is_login"]=true

request.session["User"]=username

Return Redirect ("/index/")

Django will do three things:

1. Create a random string. If s= "Sdgsdfg4565dfgsdfgsdf"

2. In the Django-session table, add a record

The Django-session has three fields, namely: Session_key,session_data,expire_data

SQL: statement: INSERT into django-session values (s, "{" Is_logon ": True," USER ": Egon}", 12321)

3, to the browser settings SessionID:obj.set_cookie ("SessionID", s)

REDIRECT After execution:

/home/----> {"SessionID": "Fasdlkfjsakdl324ada2adhdjlka99"}

Request.session.get ("Is_logon", None)

In the Django-session table, make a query:

S=requset. Cookie.get ("SessionID")
Select Session-data from Django-session where session-key=s

3. Example

views.py

def log_in (Request): If request.method== "POST": Username=request. post[' user '] password=request. post[' pwd '] user=userinfo.objects.filter (username=username,password=password) if User: #设置session Internal dictionary content request.session[' is_login ']= ' true ' request.session[' username ']=username #登录成功就将ur L redirect to backend URL return redirect ('/backend/') #登录不成功或第一访问就停留在登录页面 return render (Request, ' login.html ') def Backe nd (Request): Print (request.session, "------cookie") print (request.     COOKIES, '-------Session ') "" "Here you must use the Get () method of the Read dictionary to set the value of Is_login to False by default, and when the user accesses backend this URL first attempts to obtain the corresponding session in the browser The value of the Is_login. If the login succeeds, the value of Is_login is changed to true in login, and the value is False "" "Is_login=request.session.get (' Is_login ', False) #如果 To be true, it means that the user is normally logged in if Is_login: #获取字典的内容并传入页面文件 cookie_content=request. COOKIES session_content=request.session username=request.session[' username ') return renDer (Request, ' backend.html ', locals ()) Else: "" If you do not have the correct session at the time of the visit, you are redirected directly to the URL back to the login page "" "Return redirect ('/login/') def log_out (Request):" "" when returning back directly through request.session[' Is_login '), if is_login corresponds to A value that does not exist causes a program exception. So you need to do exception handling "" "Try: #删除is_login对应的value值 del request.session[' Is_login ') # OR---- ; Request.session.flush () # Delete the corresponding row of records in the Django-session table except Keyerror:pass #点击注销之后, redirect directly back to the login page return redir ECT ('/login/')

  

Template

===================================login.html==================<! DOCTYPE html>

  

4, session storage of the relevant configuration

(1) The default is the database configuration:

#Django默认支持Session, and by default the session data is stored in the database, namely: Django_session table.  #配置 settings.py      Session_engine = ' django.contrib.sessions.backends.db '   # engine (default)          session_cookie_name = "SessionID"                       # Session cookie saved on browser key, i.e.: sessionid= random string (default)    Session_cookie_path = "/"                               # SESSION Cookie saved Path (default)    Session_cookie_domain = None                             # SESSION COOKIE saved domain name (default)    session_cookie_secure = False                            # Whether the HTTPS transport cookie (default)    session_cookie_httponly = True                           # If the SESSION's cookie only supports HTTP transport (default)    Session_cookie_ Age = 1209600                             # SESSION Cookie Expiration date (2 weeks) (default)    session_expire_at_browser_close = False                  # Whether to close the browser so that the session expires (default)    session_save_every_request = False                       # Whether each request is saved session, the default is not saved after the change (default)

  

(2) Cache configuration

#配置 settings.py      session_engine = ' Django.contrib.sessions.backends.cache '  # engine    Session_cache_alias = '                            the cache alias (default memory cache, or memcache) used by the alias, where the aliases depend on the cache settings      session_cookie_name = "SessionID"                        # The session's cookie is stored on the browser when the key, namely: Sessionid= random string    Session_cookie_path = "/"                                # SESSION of the cookie saved path    session_ Cookie_domain = None                              # SESSION cookie saved domain name    session_cookie_secure = False                             # Whether HTTPS transport cookie    Session_cookie_httponly = True                            # Whether the SESSION's COOKIE only supports HTTP transport    session_cookie_age = 1209600                              # Session cookie Expiration Date (2 weeks)    session_expire_at_browser_close = False                   # whether to close the browser so that the session expires    Session_save_ Every_request = False                        # If the session is saved every time the request is changed, it is saved after the default modification

  

(3) file configuration

#配置 settings.py      session_engine = ' django.contrib.sessions.backends.file '    # engine    Session_file_path = None                                    # Cache file path, if none, use the Tempfile module to get a temporary address tempfile.gettempdir ()            Session_cookie_name = "SessionID"                          # SESSION of the COOKIE is stored on the browser when the key, that is: sessionid= random string    Session_cookie_path = "/"                                  # Session Cookie Save path    Session_cookie_domain = None                                # SESSION cookie saved domain name    session_cookie_secure = False                               # whether HTTPS transport cookie    session_cookie_httponly = True                              # Whether the SESSION's COOKIE only supports HTTP transport    session_cookie_age = 1209600                                # Session cookie Expiration Date (2 weeks)    session_expire_at_browser_close = False                     # whether to close the browser so that the session expires    Session_save_ Every_request = False                          # If the session is saved every time the request is changed, it is saved after the default modification

  

Python Web framework "supplemental" Cookie and session (Django)

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.