1024programmer Java How to use Session outside of Django’s View

How to use Session outside of Django’s View

Internally, each session is just a regular Django model (defined in django.contrib.sessions.models). Each session is identified by a random 32-byte hash string and stored in COOKIE. Because it is a standard model, you can use the Django database API to access the session.

 >>> from django.contrib.sessions.models import Session
 >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
 >>> s.expire_date
 datetime.datetime(2005, 8, 20, 13, 35, 12)

 

You need to use get_decoded() to read the actual session data. This is required because the dictionary is stored in a specific encoding format.

 >>> s.session_data
 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
 >>> s.get_decoded()
 {'user_id': 42}

 

When to Save Session

By default, Django will only save it to the database when the session changes, such as dictionary assignment or deletion.

 # Session is modified.
 request.session['foo'] = 'bar'

 # Session is modified.
 del request.session['foo']

 # Session is modified.
 request.session['foo'] = {}

 # Gotcha: Session is NOT modified, because this alters
 # request.session['foo'] instead of request.session.
 request.session['foo']['bar'] = 'baz'

 

You can change this default behavior by setting SESSION_SAVE_EVERY_REQUEST to True. If set to True, Django will save the session every time it receives a request, even if there are no changes.

Note that session cookies will only be sent when they are created and modified. But if SESSION_SAVE_EVERY_REQUEST is set to True, the session cookie will be sent on every request. At the same time, every time a session COOKIE is sent, its expires parameter will be updated.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/787625

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索