Enable session?
Conversations are implemented through middleware.
To enable the session function, you need to complete the following steps:
Modify the MIDDLEWARE_CLASSES setting and ensure that it contains "django.contrib.sessions.middleware.session middleware". The default settings.py created by django-admin.py startproject has activated SessionMiddleware.
Add "django.contrib.Sessions" to the INSTALLED_APPS setting and execute manage.py syncdb to install the table for storing session data.
Change in Django 1.0: If you don't use the database to store the session, you can ignore this step; Refer to Configuring the Session Engine.
If you don't want to use sessions, you can also delete the SessionMiddleware line from MIDDLEWARE_CLASSES and' django.contrib.sessions' from INSTALLED_APPS. This will save you a little money.
Configure the session engine?
New functions in Django 1.0 ..
By default, Django stores sessions in the database (using the model django. contrib.sessions.models.session). Although this is convenient, in some cases, it is faster to put the conversation somewhere else. So Django allows you to configure it to save session data in a file system or a buffer.
Use a file-based session?
To use a file-based session, set the SESSION_ENGINE to "django.contrib.sessions.backs.file".
You may also need to modify the setting of SESSION_FILE_PATH to control where Django stores session files. By default, it uses tempfile.gettempdir (), usually /tmp.
Use a buffer-based session?
To save a session using Django's buffer system, you need to set the SESSION_ENGINE to "django.contrib.sessions.backs.cache". You must ensure that the buffer has been configured, please refer to the buffer documentation for details.
pay attention to
Buffer-based sessions can only be used when Memcached is used as a buffer background. Because when local memory is used as the buffer background, the time for storing buffered data is too short, so the speed of accessing files or databases directly is faster than that of accessing files or databases through buffering.
Use session in view?
After opening the sessionMiddleware, each HttpRequest object (the first parameter of the Django view function) has a session attribute, which is a class dictionary object. You can read and write it directly.
Session objects have the following standard dictionary functions:
__getitem__ (keyword)
Example: fav _ color = request.session ['fav _ color']
__setitem__ (key, value)
Example: request.session ['fav _ color'] =' blue'
_ _ delivery _ _ (keyword)
Example: delrequest.session ['fav _ color']. This will cause a key error if the given key is not in session.
_ _ contains _ _ (keyword)
Example: "fav _ color" in request.session
Get (key, default = none)
Example: fav _ color = request.session.get ('fav _ color',' red').
Press the key ()
Project ()
setdefault()
Clear ()
Django 1.0 added: set default () and clear () are added in this version.
It also has the following methods:
Flush ()
New functions in Django 1.0.
Delete the current session data from the database, regenerate the session key and send it to the browser. You can use this method when you need to ensure that the session data can no longer be accessed from the user's browser, such as calling django.contrib.auth.logout ().
set_test_cookie()
Set the detection Cookie to check whether the user's browser supports cookies. Because of the way Cookie work, you won't get the test results until the next user requests them. For more information, refer to the following settings to detect Cookie.
test_cookie_worked()
Determines whether the user's browser has received the detection Cookie and returns True or False. Because of the way cookies work, you must call set_test_cookie () in the previous independent request. For more information, refer to the following settings to detect Cookie.
delete_test_cookie()
Delete the detection Cookie, please call this function to clear the Cookie yourself.
Set_expiry (value)
New functions in Django 1.0.
Set the expiration time of the session. You can provide the following values:
If value is an integer, it represents seconds. Like calling for it. Session.set _ expire (300) will make the session expire in five minutes.
If value is a datetime or timedelta object, the session will expire on the corresponding date or time.
If the value is 0, the user's session will expire when the browser is closed.
If the value is None, the session will use the global policy to set the expiration time.
get_expiry_age()
New functions in Django 1.0.
Gets the expiration time of this session. For sessions without a custom expiration time (or sessions that expire when the browser is closed), the return value of this function is the same as settings. Session _COOKIE_AGE.
get_expiry_date()
New functions in Django 1.0.
Gets the expiration point of this session. For sessions with no custom expiration time (or sessions that expire when the browser is closed), the return value of this function is equal to the number of seconds set from now to the time point. Session _COOKIE_AGE.
get_expire_at_browser_close()
New functions in Django 1.0.
Returns whether the session expired when the browser was closed, and the return value is True or False.
You can modify request.session any number of times at any position in the view.
Session object guide?
Use Python strings directly as the key of the dictionary according to the request. Session is more direct than using the session object.
In the conversation dictionary, keys that start with an underscore are reserved for Django's internal use.
Do not overwrite request.session with a new object, or access or modify its properties. It can only be used as a class dictionary object.
For example?
This simple view sets the variable has_commented to True after the user submits the evaluation information to prevent the user from submitting the evaluation information multiple times:
Def post_comment(request, new _ comment): if request.session.get ('has _ commented', False): return HttpResponse ("You have already commented." ) c = comment. Comment (comment = new _ comment) c.save () request.session ['has _ commented'] = true return httpresponse ('Thank you for your comment!' )
This simple view allows "users" of the website to log in:
Def login (request): m = Member.objects.get (user name = request. POST['username']) If m.password == request. Post ['password']: request.session ['member _ id'] = m.id return httpresponse ("You are logged in." Else: returns HttpResponse ("Your username and password don't match." )
... corresponding to the above example, the following example lets the user exit:
Deflogout (request): try: delrequest.session ['member _ id'] except key error: pass return httpresponse ("You have logged out." )
In fact, the standard django.contrib.auth.logout () will do more to prevent data leakage caused by negligence. It calls the request.session.flush () function. We only use these examples to demonstrate how to manipulate session objects, which is not a complete login () implementation.
Set detection Cookie?
For convenience, Django provides a simple way to detect whether a user's browser supports Cookie. Just call request.session.set _ test _ cookie () in one request, and call request.session.test _ cookie _ worked () in subsequent requests. Be careful not to call at the same time in the same request.
Set_test_Cookie () and test_Cookie_worked () are called in two requests because of the working mode of cookies. When you set a Cookie, there is no way to know whether the browser will receive it before the next request.
In addition, it is best to use delete_test_cookie () to clear the test data after the test.
The following is a typical example:
Def login (request): ifrequest.method = =' post': ifrequest.session.test _ cookie _ worked (): request.session.delete _ test _ cookie () Return httpresponse ("You are logged in." ) else: return HttpResponse ("Please enable cookies and try again." )request . session . set _ test _ cookie()return render _ to _ response(' foo/log in _ form . html ')
Use a session out of view?
New functions in Django 1.0.
There is an API dedicated to manipulating session data outside the view:
& gt& gt& gt Import session from django.contrib.sessions.backs.db & gt> = SessionStore (session _ key =' 2b1189a1 88 b 44 ad 18 c 35 e 1 13 AC 6 ceead ')& gt; & gt>S ['last _ login'] = datetime. datetime (2005,8,20,13,35,10) >>>S ['last _ login'] datetime. datetime (2000)
If you use the django.contrib.sessions.backs.db background, then each session is an ordinary django model. Model sessions are defined in the file django/contrib/sessions/models.py. Because it is a general model, you can access it directly by using Django's database programming interface:
& gt& gt& gt Import session from django.contrib.sessions.models & gt>S = session.objects.get (PK =' 2b1189a188b44ad18c. & gt& gt date and time (August 20, 2005, 13, 35, 12)
Note that to get the session dictionary, you need to call get_decoded (), because the dictionary is stored in an encoded way:
& gt& gt& gts . session _ data ' kgrwmqptj 19 hdx rox 3 vzzxjfawqncnayckkxcnmumtexy 2 zjodi 2 yj ... '& gt& gt& gts.get_decoded() {'user_id': 42}
When was the session stored?
By default, Django saves a session only when it is modified, that is, only when the values in the dictionary are modified or deleted:
# Session has been modified. Request.session ['foo'] =' bar' # session has been modified. Del request.session['foo'] # Session has been modified. Request.session ['foo'] = {} # Gotha: Do not modify the session, because this will change # request.session['foo'] instead of request.session.request.session ['foo'] ['bar'] =' baz'
For the last one above, you can notify the session object that it has been modified by explicitly setting the modified property of the session object:
request.session.modified = True
To change this behavior, you can set SESSION_SAVE_EVERY_REQUEST to True. If SESSION_SAVE_EVERY_REQUEST is True, Django will save the session after each independent request.
Note that the session Cookie is sent only when the session is created or modified. If SESSION_SAVE_EVERY_REQUEST is True, a cookie will be sent every time a request is made.
Similarly, when a Cookie is sent, its expired part is updated every time.
Sessions are synchronized with browsers and persistent sessions?
By setting session _ expire _ at _ browser _ close, you can control the session framework to use a session synchronized with the browser or a persistent session.
By default, the value of session _ expire _ at _ browser _ close is False, which means that the session Cookie will be saved in the user's browser until the SESSION_COOKIE_AGE is exceeded. Use this method if you want users to stop logging in every time they close the browser.
If session _ expire _ at _ browser _ close is set to True, Django will use a Cookie synchronized with the browser, that is, the Cookie will expire when the user closes the browser. Use this mode if you want users to log in every time they open a browser.
New functions in Django 1.0.
This setting has a global default value, but you can set an independent value for each session by calling request. Conversation. Set _ expire (), related content is described in the above-mentioned using conversation view.
Clear the session table?
Note that session data may accumulate in the database table Django_session, and Django does not provide the function of automatically clearing them. It leaves you with the task of periodically emptying session data.
To understand this problem, imagine what happens when users use Session. When the user logs in, Django adds a record to the django_session table. Django updates this record whenever the session data changes. If the user logs off manually, Django will delete it. However, if the user does not quit, the record will never be deleted.
Django provides a sample script django-admin.py cleanup, which can complete the cleaning function. It deletes records from the session table that have expire_date, but your application may have other requirements.
Settings?
Some Django settings can help you control the behavior of the session:
Session _ Engine?
New functions in Django 1.0.
Default value: django.contrib.sessions.backs.db.
Controls where Django saves session data. Legal values include:
' django . contrib . sessions . backends . db '
' django . contrib . sessions . backends . file '
' django . contrib . sessions . back ends . cache '
For more information, refer to Configuring the Session Engine.
Session _ File _ Path?
New functions in Django 1.0.
Default value: /tmp/
If file-based session storage is used, this variable controls the directory where Django stores session data.
SESSION_COOKIE_AGE?
Default value: 1209600 (two weeks, in seconds)
The expiration time of the session Cookie, in seconds.
SESSION_COOKIE_DOMAIN?
Default: None
The domain of the session Cookie. If you want to set cross-domain Cookie, you can set them in the form of "lawrence.com", otherwise, please use None.
Session _COOKIE_NAME?
Default value: "Session id"
The name of the Cookie used by the session can be set as required.
SESSION_COOKIE_SECURE?
Default value: False
Whether to use safe mode for session Cookie. If set to True, Cookie will be marked as "safe". In this case, the browser needs to determine whether the Cookie is sent over an HTTPS connection.
SESSION _ EXPIRE _ AT _ browser _CLOSE?
Default value: False
Whether to let the session expire when the user closes the browser. For more information, please refer to browser-synchronized sessions and persistent sessions above.
Session _ Save _ Every request?
Default value: False
Whether to save the session data for each request. If this item is False (the default value), the session data will be saved only after it is modified, that is, when its dictionary value is assigned or deleted.
Technical details?
The conversation dictionary can accept any Python object compatible with pickle. Please refer to the pickle module for details.
Session data is stored in the database table django_session.
Django only sends cookies when necessary. If you do not set any session data, it will not send cookies.
Session ID in URL?
Django's conversation framework is completely based on cookies and can only be based on cookies. It doesn't put the session ID in the URL when the session doesn't work properly, like some software (such as PHP). This decision was made after careful consideration. That method not only makes the URL ugly, but also makes the session ID leak through the "Referer" header, which brings security risks to the website.