{"id":5587,"date":"2022-11-16T02:40:20","date_gmt":"2022-11-16T02:40:20","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=5587"},"modified":"2022-12-03T04:35:17","modified_gmt":"2022-12-03T04:35:17","slug":"django-sessions","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/django-tutorial\/django-sessions\/","title":{"rendered":"Django Sessions"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about how Django sessions work and how to set various settings for the session.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-django-sessions'>Introduction to Django sessions <a href=\"#introduction-to-django-sessions\" class=\"anchor\" id=\"introduction-to-django-sessions\" title=\"Anchor for Introduction to Django sessions\">#<\/a><\/h2>\n\n\n\n<p>Django has a session framework that supports both anonymous and user sessions. Django uses the session middleware to send and receive cookies.<\/p>\n\n\n\n<p>The following picture illustrates how the Django sessions work:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"806\" height=\"531\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions.png\" alt=\"django sessions\" class=\"wp-image-5597\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions.png 806w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-300x198.png 300w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-768x506.png 768w\" sizes=\"auto, (max-width: 806px) 100vw, 806px\" \/><\/figure>\n\n\n\n<p>When a web browser makes the first HTTP request to the web server, the session middleware starts a new session. The session middleware generates a large and random number which is called a session identifier and sends it back to the web browser as a cookie.<\/p>\n\n\n\n<p>For the subsequent requests, the session middleware matches the value <code>sessionid<\/code> in the cookie sent by the web browser with the session identifier stored on the web server and associates the session data with the HTTP request object.<\/p>\n\n\n\n<p>To use sessions, you need to ensure that the <code>MIDDLEWARE<\/code> settings of your project (<code>settings.py<\/code>) contain the session middleware like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-code-table\"><span class='shcb-loc'><span>MIDDLEWARE = &#91;\n<\/span><\/span><span class='shcb-loc'><span>    <span class=\"hljs-comment\"># other middleware<\/span>\n<\/span><\/span><mark class='shcb-loc'><span>    <span class=\"hljs-string\">'django.contrib.sessions.middleware.SessionMiddleware'<\/span>,\n<\/span><\/mark><span class='shcb-loc'><span>    <span class=\"hljs-comment\"># ...<\/span>\n<\/span><\/span><span class='shcb-loc'><span>]\n<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The session middleware is added to the <code>MIDDLEWARE<\/code> by default when you create a new project using the <code>startproject<\/code> command.<\/p>\n\n\n\n<p>The session middleware enables sessions via the <code>session<\/code> property of the request object (<code>HttpRequest<\/code>):<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.session<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>request.session<\/code> is a dictionary that allows you to store and retrieve session data. The <code>request.session<\/code> accepts any object that can be serialized to JSON by default.<\/p>\n\n\n\n<p>Unlike other objects, the <code>request.session<\/code> persists from one HTTP request to the next request.<\/p>\n\n\n\n<p>To set a variable in the session, you can use the <code>request.session<\/code> like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.session&#91;<span class=\"hljs-string\">'visit'<\/span>] = <span class=\"hljs-number\">1<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This statement sets the visit variable to 1.<\/p>\n\n\n\n<p>To retrieve a session key, you use the <code>get()<\/code> method of the <code>request.session<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.session.get(<span class=\"hljs-string\">'visit'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To delete a key in the session, you use the <code>del<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">del<\/span> request.session&#91;<span class=\"hljs-string\">'visit'<\/span>]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='setting-django-sessions'>Setting Django sessions <a href=\"#setting-django-sessions\" class=\"anchor\" id=\"setting-django-sessions\" title=\"Anchor for Setting Django sessions\">#<\/a><\/h2>\n\n\n\n<p>By default, Django stores session data in a database using the <code>Session<\/code> model of the <code>django.contrib.sessions<\/code> application. However, you can choose other session engines using the <code>SESSION_ENGINE<\/code>.<\/p>\n\n\n\n<p>Django provides you with the following options for storing session data:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Options<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td>Database sessions<\/td><td>Store session data in the django_session of the database. This is the default engine.<\/td><\/tr><tr><td>File-based sessions<\/td><td>Store session data in the filesystem.<\/td><\/tr><tr><td>Cached sessions<\/td><td>Store session data in a cache backend. To set the cache backend, you use the <code>CACHES<\/code> setting.<\/td><\/tr><tr><td>Cached database sessions<\/td><td>Store session data in a write-through cache and database. If the data is not in the cache, Django will read the session data from the database.<\/td><\/tr><tr><td>Cookie-based sessions<\/td><td>Store session data in the cookies that are sent to the web browser.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Note that a cache-based session engine provides better performance in comparison with other session engines. <\/p>\n\n\n\n<p>Django supports Memcached out of the box. In addition, you can find a third-party package for managing cache backends for Redis and other cache systems.<\/p>\n\n\n\n<p>Besides the <code>SESSION_ENGINE<\/code>, Django allows you to customize sessions with specific settings. The following table list the most important ones:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Session settings<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td>SESSION_COOKIE_AGE<\/td><td>The duration of session cookies in session. The default is two weeks (1,209,600 seconds)<\/td><\/tr><tr><td>SESSION_COOKIE_DOMAIN<\/td><td>Set the domain for session cookies. <\/td><\/tr><tr><td>SESSION_COOKIE_HTTPONLY<\/td><td>Set to True to prevent JavaScript from accessing the session cookie. It defaults to True, which increases security against user session hijacking.<\/td><\/tr><tr><td>SESSION_COOKIE_SECURE<\/td><td>Set to True to indicate that the cookie should only be sent if the connection is an HTTPS connection. It defaults to False.<\/td><\/tr><tr><td>SESSION_EXPIRE_AT_BROWSER_CLOSE<\/td><td>Set to True to expire the session when you close the browser. Its default value is False. If you set this to True, the SESSION_COOKIE_AGE won&#8217;t have any effect.<\/td><\/tr><tr><td>SESSION_SAVE_EVERY_REQUEST<\/td><td>Set to True to save the session and update session expiration to the database on every request. It defaults to False.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id='django-sessions-example'>Django sessions example <a href=\"#django-sessions-example\" class=\"anchor\" id=\"django-sessions-example\" title=\"Anchor for Django sessions example\">#<\/a><\/h2>\n\n\n\n<p>First, add a URL to the <code>urlpatterns<\/code> in the <code>urls.py<\/code> file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">urlpatterns = &#91;\n    path(<span class=\"hljs-string\">'visit\/'<\/span>, views.count_visit, name=<span class=\"hljs-string\">'visit'<\/span>)\n]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When you navigate to <code>http:\/\/localhost:8000\/visit<\/code>, the <code>count_visit<\/code> function in views.py will execute.<\/p>\n\n\n\n<p>Second, define the <code>count_visit()<\/code> function in the <code>views.py<\/code> file: <\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">count_visit<\/span><span class=\"hljs-params\">(request)<\/span>:<\/span>\n    visit = request.session.get(<span class=\"hljs-string\">'visit'<\/span>,<span class=\"hljs-number\">0<\/span>) + <span class=\"hljs-number\">1<\/span>\n    request.session&#91;<span class=\"hljs-string\">'visit'<\/span>] = visit\n    <span class=\"hljs-keyword\">return<\/span> HttpResponse(<span class=\"hljs-string\">f\"Visit count:<span class=\"hljs-subst\">{request.session&#91;<span class=\"hljs-string\">'visit'<\/span>]}<\/span>\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>count_visit()<\/code> function uses the <code>request.session<\/code> to increase the <code>visit<\/code> variable each time you visit the <code>http:\/\/localhost:8000\/visit<\/code> URL. It also displays the current value of the <code>visit<\/code> variable on the web page:<\/p>\n\n\n\n<figure class=\"wp-block-video\"><video height=\"120\" style=\"aspect-ratio: 460 \/ 120;\" width=\"460\" controls src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/Django-Sessions.mp4\"><\/video><\/figure>\n\n\n\n<p>If you view the cookies in the web browser, you&#8217;ll see a cookie with the name sessionid:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"976\" height=\"285\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-cookies.png\" alt=\"django sessions - cookies\" class=\"wp-image-5604\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-cookies.png 976w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-cookies-300x88.png 300w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-cookies-768x224.png 768w\" sizes=\"auto, (max-width: 976px) 100vw, 976px\" \/><\/figure>\n\n\n\n<p>The value of the sessionid is corresponding with the session_key in the django_session table:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"969\" height=\"63\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-database.png\" alt=\"django sessions - database\" class=\"wp-image-5606\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-database.png 969w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-database-300x20.png 300w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-sessions-database-768x50.png 768w\" sizes=\"auto, (max-width: 969px) 100vw, 969px\" \/><\/figure>\n\n\n\n<p>The session data is a string encoded using base64. To analyze it, you use the following code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> base64 <span class=\"hljs-keyword\">import<\/span> b64decode\n\ndata = base64decode(<span class=\"hljs-string\">'eyJ2aXNpdCI6MTF9:1ov84c:qngX5Woil1EDwGGylot0OrQtche6734UOApKJ4yp-BA'<\/span>)\nprint(data)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">b'{\"visit\":11}\\xd6\\x8b\\xfc\\xe1\\xca\\xa7\\x81~V\\xa2)u\\x10&lt;\\x06\\x1b)h\\xb7C\\xabB\\xd7!{\\xae\\xf7\\xe1C\\x80\\xa4\\xa2x\\xca\\x90@'<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A session is a variable that lives across requests.<\/li>\n\n\n\n<li>Django uses session middleware to manage sessions.<\/li>\n\n\n\n<li>Use <code>request.session<\/code> to manage session data.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"5587\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-sessions\/\"\n\t\t\t\tdata-post-title=\"Django Sessions\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"5587\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-sessions\/\"\n\t\t\t\tdata-post-title=\"Django Sessions\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you&#8217;ll learn about how Django sessions work and how to set various settings for the session. Introduction to Django sessions # Django has a session framework that supports both anonymous and user sessions. Django uses the session middleware to send and receive cookies. The following picture illustrates how the Django sessions [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":5531,"menu_order":44,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-5587","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5587","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=5587"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5587\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5531"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=5587"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}