Ajax (ii)

Source: Internet
Author: User
Tags set cookie unique id

COOKIE and Session Introduction

1, the cookie does not belong to the HTTP protocol scope, because the HTTP protocol cannot maintain the state, but actually, we need to "maintain the state", therefore the cookie is born in such a scene.

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.

2, although the cookie to some extent solves the "keep state" demand, but because the cookie itself supports 4096 bytes, and the cookie itself is saved on the client, may be intercepted or stolen, so there is a need for a new thing, it can support more bytes, and he saved in the server , and 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.

3, IN summary: The cookie makes up for the lack of HTTP stateless, let the server know the person is "who", but the cookie as text in the form of local, self-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.

4. In addition, the above mentioned cookie and session is in fact a common thing, not limited to language and framework

Certified applications

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}

Now that we know the principle, we'll use code to implement it.

Cookies
def foo (request):    print (Request. COOKIES)    obj=redirect ("/path/")    obj=httpresponse ("content")    Obj=render (Request, "HTML")    Obj.set _cookie ("Key", "value", max_age=60,path= "/path/")    Obj.set_signed_cookie ("Key", "value", max_age=60,path= "/path /", salt=" EGONNB ")    Request.get_signed_cookie (" Key ", salt=" EGONNB ");    return obj
SESSION

Create two html,login.html in the Templates directory to be responsible for the login page first. Backend page represents a background page

Login.html

<!    DOCTYPE html>

Backend.html

 <!    DOCTYPE html>

The third step is to edit the urls.py file under the Mydjango directory. To set the binding relationship of a function to a page

urls.py

From django.conf.urls import urlfrom django.contrib import adminfrom app01 Import viewsurlpatterns = [    url (r ' ^admin/') , admin.site.urls), url (r ' ^login/', views.login), url (r '    ^backend/', views.backend), url    (r ' ^logout/', Views.logout),]

Finally, when you open the browser directly to the/backend/page, you are redirected directly to the/login/

Enter the/backend/page only after you have entered the correct username and password

We can see a few points from it:

1, login page correctly login, background page can get to the browser to carry the cookie.

2, the first line of SessionID is actually the cookie value

3, session content is encrypted, from the client to get the content of the session

4, the server can use the preset key value to remove the contents of the session and print to the previous paragraph

View cookies from Firefox browser

Django's session is stored in the database by default, and we'll go to the database to see what the real session is.

We can see a few points from it:

1, login page correctly login, background page can get to the browser to carry the cookie.

2, the first line of SessionID is actually the cookie value

3, session content is encrypted, from the client to get the content of the session

4, the server can use the preset key value to remove the contents of the session and print to the previous paragraph

View cookies from Firefox browser

Django's session is stored in the database by default, and we'll go to the database to see what the real session is.

Let's take a final look at the cookie and session knowledge points

Cookies:

# 1, Get cookie:# request. cookies[' key ']# Request.get_signed_cookie (Key, Default=raise_error, salt= ', max_age=none) #     parameter: #         default: Default Value #            Salt: Crypto Salt #         max_age: Background Control Expiration # 2, set cookie:# rep = HttpResponse (...) or rep = render (Request, ...) # # Rep.set_cookie (Key,value,...) # Rep.set_signed_cookie (key,value,salt= ' crypto Salt ',...) #     Parameters: #         key,              key #         value= ',         value #         Max_age=none,     timeout #         Expires=none, Time     -out (IE Requires expires, so set it if hasn ' t been already.) #         path= '/',         cookie takes effect path,/indicates root path, Special: Cookie with path can be accessed by any URL of page #         Domain=none,      cookie in effect domain #         Secure=false,     HTTPS transport #         Httponly=false can    only be transmitted by the HTTP protocol and cannot be obtained by JavaScript (not absolute, the underlying capture can be obtained or overwritten) # Because cookies are stored on the client's computer, JavaScript and jquery can also manipulate cookies. # <script src= '/static/js/jquery.cookie.js ' ></script># $.cookie ("List_pager_num", 30,{Path: '/'});
View Code

Session

The default support session in Django provides 5 types of sessions for developers to use:

    • Database (default)
    • Cache
    • File
    • Cache + Database
    • Encrypt cookies

1. Database session

Django supports session by default, and the session data is stored in the database by default, which is: Django_session table. A. Configuring settings.py Session_engine = ' django.contrib.sessions.backends.db ' # engine (default) Session_cookie_name = "ses                               Sionid "# SESSION of the COOKIE is saved on the browser when the key, that is: 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 HTTPS transport COOKIE (default) session_cookie_httponly = Tru E # whether 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 # Do you want to save the session every time you request it (default) B. Use DEF index (request): # GET, set, delete data in session request.session[' K1 ' request.session.get (' K1 ', NoNE) request.session[' k1 '] = 123 request.session.setdefault (' K1 ', 123) # exists then does not set del request.session[' K1        '] # All keys, values, key value pairs Request.session.keys () request.session.values () Request.session.items () Request.session.iterkeys () request.session.itervalues () Request.session.iteritems () # User session with         Machine String 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 ("Session_key") in the database # Delete all session data for the current user request.ses Sion.delete ("Session_key") ...
View Code

2. Cache session

A. Configuring 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 each time the request is changed, B is saved after the default   . Use     Ibid.
View Code

3, File session

A. Configuring 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 ()                          # such as:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/t session_cookie_name = "SessionID"                                  # SESSION of the COOKIE is saved on the browser when the key, that is: sessionid= random string session_cookie_path = "/" # Session Cookie Saved Path Session_cookie_domain = None # session cookie saved domain name SESSI                              On_cookie_secure = False # Whether HTTPS transport COOKIE session_cookie_httponly = True # is the cookie for session only supports HTTP transfer session_cookie_age = 1209600 # session cookie Loss Validity date (2 weeks) Session_expire_at_browser_close = False # whether to close the browser so that the SESSION expires Session_save_every_request                 = False         # Do you want to save the session for each request, and then save B after the default change? Use Ibid. 
View Code

4. Cache + Database Session

The database is used for persistence, and the cache is used to improve the efficiency a. Configure settings.py     session_engine = ' django.contrib.sessions.backends.cached_db '        # Engine B. Using the c3/> Ibid.
View Code

5. Encryption Cookie Session

A. Configuring settings.py         session_engine = ' django.contrib.sessions.backends.signed_cookies '   # engine B. Use     ibid.
View Code

Extension: Session user authentication

def login (func):    def wrap (request, *args, **kwargs):        # If not logged in, jump to the specified page if        request.path = = '/test/':            Return redirect (' http://www.baidu.com ') return        func (Request, *args, **kwargs)    return wrap
View Code

Ajax (ii)

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.