Django Sessions (session)

Source: Internet
Author: User

Django Session

Django provides full support for anonymous sessions, and the session framework can store and retrieve arbitrary data for each site visitor. Session data is stored on the server side, and the process of sending and accepting cookies is briefly provided, and the cookies contain only one session ID rather than the data itself, unless you are using a cookie-based backup of the conversation.

Let's take a look at how to use the session framework.

Enable session

The session is implemented through a middleware. So if you want to enable the session function, you just need to join Django.contrib.sessions.middleware.SessionMiddleware on middleware_classes .

If you create a project using django-admin.py Startproject, the default is to enable this feature, so if you do not want to use the sessions function, remember to remove the corresponding item in Middleware_class,

And, remember to remove sessions in Installed_apps, which saves you a little bit of database space

Configuring the Session Engine

Default Django stores sessions in your database (using the Django.contrib.sessions.models.Session model)

While this is convenient, sometimes storing sessions elsewhere can make access faster, let's look at a variety of ways to configure the session engine.

Using a database-supported session

The default method, you need to add django.contrib.sessions to the Installed_apps settings

Then run manage.py syncdb to generate the corresponding table in the database

Using a cached session

If you want your system to perform better, you might consider using cache-based backend processing, but if you cache, you first need to configure your cache

Once the cache is configured, you have two choices on how to store data in the cache

    • With Django.contrib.sessions.backens.cache configuration Session_engin, the session is stored directly in the cache, and once the cache is full or the cache server restarts, all data is lost
    • Using django.contrib.sessions.backends.cached_db configuration Session_engin, which is a write-through cache, each write to the cached data is also written into the database, only when the session is not in the cache, access to the database

Both of these options are fast, and the first cache is faster than cached_db because there is no database interaction, but in general, cached_db is fast enough, and if it needs to be faster, consider the cache

Note that the cached_db is also used in the database, remember to refer to the above using database-supported sessions

Using a file-based session

To use a file-based session, remember to set Session_engin to Django.contrib.sessions.backends.file, and you might want to set Session_file_path to control the Django storage session, Make sure the Django server has permission to read and write to that location.

Using a cookie-based session

To use a cookie-based session, you only need to set Session_engin to Django.contrib.sessions.backends.signed_cookies, Those session data will use Django's cryptographic signature tool and Secret_key to store the data.

Tip: It is recommended to put session_cookie_httponly=true so that you can prevent access to JavaScript-stored data

Remind:

    • Session data is signed but not encrypted: the client can read or even change the data, or the size of the cookie is discarded as part of the browser's default length, which makes the session data invalid
    • No guarantee of freshness: The MAC (message Verification code) guarantees the authenticity and completeness of the data, but does not guarantee the freshness of the message, which may result in a "replay attack" and the COOKIE is considered "obsolete" only if it is earlier than Session_cookie_age.
    • Operating performance: The size of the cookie affects the speed of access to your website
Using a session in a view function

Once the session middleware is enabled, each HttpRequest object-the first parameter of each Django view function-will have a session property, which is a dictionary-like object, You can use request.session anywhere in your view function, you can use multiple

The following pseudo-code shows the standard dictionary method of the session

classBackends.base.SessionBase#this is the base class for all session objects, and here are some standard dictionary methods__getitem__(Key)#Example:fav_color = request.session[' Fav_color ']__setitem__(key, value)#example:request.session[' fav_color ' = ' Blue '__delitem__(Key)#example:del request.session[' Fav_color ']. If key does not exist, as in the standard dictionary, a keyerror error will be thrown__contains__(Key)#Example: ' Fav_color ' in Request.session, returns a bool valueget (key, default=None)#Example:fav_color = request.session.get (' Fav_color ', ' red ') if get less than session,fav_color=red named Fav_colorPop (key)#Example:fav_color = Request.session.pop (' Fav_color ')#Common Dictionary methodskeys () items () SetDefault () Clear ()#There are also the following methodsFlush ()#Delete the value of the cookie (session) that has been sent to the user from the session and regenerate the key of the session to ensure that the previous session data is not accessed again, such as the Django.contrib.auth.logout () function calls this method. Set_test_cookie ()#set a test cookie to work with the following test_cookie_workedtest_cookie_worked ()#to call Set_test_cookie () first, return a bool variableDelete_test_cookie ()#Delete a tested cookieSet_expiry (value)#to set the expiration time for a session#if value is an integer, it represents the number of seconds, and the call to Request.session.set_expiry#if it is a datetime or Timedelta object, it is the corresponding time and date#If none, the global expiration policy is usedget_expiry_age ()#returns the number of seconds remaining in session expirationget_expiry_date ()#returns the date the session expiresget_expire_at_browser_close ()#returns the cookie is deleted when the browser is closed, is a bool variable cookie will expire when the user's Web browser is closed.

Session Object Guide

    • When using request.session, use them like a python string
    • The keys that start with the underscore are reserved for Django internal use, and do not use the variable names that begin with an underscore
    • Do not overwrite request.session, just like using a Python dictionary type data to use his
Examples of Use

Simple to use: Set up and use session

defpost_comment (Request, new_comment):ifRequest.session.get ('has_commented', False):returnHttpResponse ("You ' ve already commented.") C= Comments.comment (comment=new_comment) c.save () request.session['has_commented'] =TruereturnHttpResponse ('Thanks for your comment!')

Set up a test cookie

defLogin (Request):ifRequest.method = ='POST':        ifrequest.session.test_cookie_worked (): Request.session.delete_test_cookie ()returnHttpResponse ("You ' re logged in.")        Else:            returnHttpResponse ("Please enable cookies and try again.") Request.session.set_test_cookie ()returnRender_to_response ('foo/login_form.html')
Cleanup Session Table

Django does not automatically delete session data that has expired, remember to run django-admin.py cleanup Delete the session table in the database that has expired

Configuration Rollup

Some Django configuration allows you to control the behavior of the session

Session_engine

Default: django.contrib.sessions.backends.db

Available options:

    • ' Django.contrib.sessions.backends.db '
    • ' Django.contrib.sessions.backends.file '
    • ' Django.contrib.sessions.backends.cache '
    • ' django.contrib.sessions.backends.cached_db '
    • ' Django.contrib.sessions.backends.signed_cookies '
Session_file_path

Default: /tmp/

Session_cookie_age

Default: 1209600 (2 weeks, in seconds)

Session_cookie_domain

Default: None

For example ". lawrence.com" (take care not to forget the dot)

Session_cookie_httponly

Default: True

Session_cookie_name

Default: ' SessionID '

Session_cookie_path

Default: '/'

Session_cookie_secure

Default: False

If true, cookies are transmitted only under HTTPS

Session_expire_at_browser_close

Default: False

Session_save_every_request

Default: False

Whether session data is saved per request

P

Django Sessions (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.