English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
As mentioned earlier, we can use cookies on the client side of the web application to store a large amount of useful data. We have already seen that we can use the client's cookies to store various data, which is very useful in web applications. This leads to the importance of saving data and some security vulnerabilities.
For security reasons, Django has a session framework to handle cookies. Sessions are used to abstractly receive and send cookies, with data stored on the server (such as in a database), and the client's cookie simply contains the session ID. Sessions also help avoid the behavior of 'do not accept cookies' set in the user's browser.
In Django, sessions are enabled in the project settings.py by adding some lines to the MIDDLEWARE_CLASSES and INSTALLED_APPS options. This should be done after the project is created, but it is always easy to know, so MIDDLEWARE_CLASSES should be similar to the following -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 'django.contrib.sessions.middleware.SessionMiddleware'
INSTALLED_APPS should have -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 'django.contrib.sessions'
By default, Django saves session information in the database (in the django_session table or collection), but it can be stored in other ways similar to the configured engine: in files or in caches.
When sessions are enabled, each request (in Django, any function that takes the first argument) has a session (dictionary) attribute.
Let's create a simple example to see how to create and save a session. We have already set up a simple login system (see the Django form handling chapter and the Django Cookies handling chapter). Let's save the username in the cookie. Therefore, if you don't log out, you won't see the login form when accessing our login page. It is more secure to use cookies handling in Django to save cookies on the server side.
For this, let's first change the login code to save the username on the server side-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 def login(request): username = 'not logged in' if request.method == 'POST': MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] request.session['username'] = username else: MyLoginForm = LoginForm() return render(request, 'loggedin.html', {'username': username})
Then let's create the view corresponding to the login form, if the cookie is set, the form will not be displayed -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 def formView(request): if request.session.has_key('username'): username = request.session['username'] return render(request, 'loggedin.html', {'username': username}) else: return render(request, 'login.html', {})
Now, let's modify the url.py file and change the URL to match the new view -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/','formView', name = 'loginform'), url(r'^login/', 'login', name = 'login'))
when accessing /myapp/connection, you will see the following page−
you will be redirected to the following page -
Now, if you try to access again/myapp/connection, it will redirect directly to the second screen.
Let's create a simple logout view to clear the Cookie.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 def logout(request): try: delete request.session['username'] except: pass return HttpResponse("<strong>You are logged out.</strong>"
and in myapp/url.py matching URL logout
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 url(r'^logout/', 'logout', name = 'logout'),
Now, if you visit/myapp/logout, the following page will be obtained-
If accessed again /myapp/connection, will get the login form (screen1)。
We have seen how to store and access sessions, and here is a good way to understand the session attributes of the request and some other useful operations, such as:
set_expiry(value) − Sets the session's expiration time
get_expiry_age() − Returns the number of seconds until the session expires
get_expiry_date() − Returns the date when the current session will expire
clear_expired() − Removes expired session storage from the session
get_expire_at_browser_close() − Returns true or false, depending on whether the user's session cookie has expired when the user's web browser closes