Cookies in Django

A cookie is a tiny data bit stored in the client’s browser. It is used to save user data in a file or specified time permanently. Your browser keeps them locally, and most browsers will display you the cookies that have been generated under the Privacy and Security settings.

HTTP as a protocol has no state. Upon request submitted to a designated server using this protocol, the server does not know if it is the user’s first visit or a repeat visit to the site. On the off chance that you log in to a website, then cookies are sent by the website—the latter details the user’s unique identification and other information relevant to the website’s context.

Cookies make it simple to incorporate certain previously impossible features using HTTP. For instance, it is automatically removed when a cookie reaches its expiration date and time. Further, Django has built-in methods for setting and retrieving cookies. The set cookie() and get() methods are used to set and get cookies, respectively.

Django fully supports anonymous sessions. The session structure allows you to store and retrieve arbitrary data per-site-visitor. It abstracts the sending and receiving of cookies by storing data on the server-side. Cookies store a session ID rather than data (unless you use a cookie-based backend).

This article seeks to elaborate on what computer cookies are and the reason to know them when dealing with the Internet. Further, we aim to decipher using the server to create Django cookies.

How do Cookies work?

It is not surprising that cookies function similarly to HTTP requests in general across the net. For instance, the browser initiates a request to the server in a typical web system manner. After that, the server transmits the response and certain cookies containing login information or other information.

The cookie produced previously is also communicated to the server when the browser makes a new request. This process is performed each time the browser makes a new request.

The process is repeated until the cookie expires or the session is closed, at which point the browser deletes the cookie.

The cookie is then used in various situations, such as logging in to a website or shopping online. It is critical to note how varied websites use cookies according to their needs. For instance, Google Analytics and Adsense strangely use cookies to keep tabs on you.

In general, here’s how cookies work:

  • The request is sent to the server by the browser.
  • The server transmits the answer to the browser and one or more cookies.
  • The cookie that the browser receives from the server is saved. The browser ensures that the cookie is sent to the server as long as it is not expired. It is done for every occasion it pings the server.
  • The cookie is deleted from the browser when it expires.

How to activate Sessions in Django

A piece of middleware is used to implement sessions. Follow these steps to activate session functionality:

Make sure that ‘django.contrib.sessions.middleware.SessionMiddleware’ is in the MIDDLEWARE configuration. Also, ensure that SessionMiddleware is enabled by default in settings.py provided by django-admin startproject.

On the off chance that you are not interested in user sessions, you can opt out by removing the SessionMiddleware from your MIDDLEWARES under the settings configuration. Further, also remove the sessions from the INSTALLED_APPS by deleting the following line ‘django.contrib.sessions’.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Setting up the session engine

By default, Django saves sessions in your database using the model django.contrib.sessions.models.Session. Though this is useful, some systems require session data to be stored elsewhere.

Django configuration is flexible so that session data is easily stored either on the cache or your filesystem.

How to use database-based sessions

You must add ‘django.contrib.sessions’ to your INSTALLED_APPS option if you wish to use a database-backed session.

Run manage.py migrate to install the single database table that keeps session data after you’ve configured your installation.

python manage.py migrate

Using previously cached sessions

You might wish to utilize a cache-based session backend for more incredible speed.

To use Django’s cache system to save session data, make sure your cache is configured correctly; For further details or clarification, check the cache documentation for more information. Django will use the default cache if multiple caches are configured in CACHES. Set SESSION_CACHE_ALIAS to the name of the cache you want to utilize.

After you’ve configured your cache, you have two options for storing data in it:

  • For a simple caching session storage, set SESSION_ENGINE to “django.contrib.sessions.backends.cache.” Session data is saved in your cache directly. On the other hand, Session data may not be persistent: if the cache fills up or the cache server is restarted, cached data is evicted.
  • Set SESSION_ENGINE to “django.contrib.sessions.backends.cached db” for permanent, cached data. It makes use of a write-through cache, which means that any changes made to the cache are likewise updated in the database. If the data isn’t already in the cache, session reads use the database.

Both session stores are quick, but the simple cache is faster because it doesn’t care about persistence. In most circumstances, the cached db backend will be enough, but if you require that extra boost and are ready to allow session data to be deleted occasionally, the cache backend is for you.

If you utilize the cached_db session backend, you must also follow the database-backed session setting instructions.

Using sessions based on cookies

Set the SESSION_ENGINE setting to “django.contrib.sessions.backends.signed cookies” to use cookies-based sessions. Django’s cryptographic signature tools and the SECRET_KEY configuration save the session data. The SESSION_COOKIE_HTTPONLY parameter should also be set to True to prohibit JavaScript from accessing the saved data.

Creating a test cookie

Django provides a means to check whether the user’s browser accepts cookies conveniently. Request’s set_test_cookie() function is used. In a subsequent view, call test cookie_worked() — not in the same view call.

The way cookies work necessitates this unpleasant separation between set_test_cookie(), and test_cookie_worked(). You won’t know whether it is accepted until the browser makes another request when you set a cookie.

Using delete_test_cookie() to clean up after yourself is a good idea. After you’ve confirmed that the test cookie worked, proceed to the next step.

Here’s an example of how to use it:

from django.http import HttpResponse
from django.shortcuts import render

def login_function(request):
  
  if request.method == 'POST':
    if request.session.test_cookie_worked():
      request.session.delete_test_cookie()
      return HttpResponse("You have logged in successfully.")
    else:
      return HttpResponse("Enable cookies before retrying.")
    request.session.set_test_cookie()
    return render(request, 'accounts/login.html')

How to Create Cookies in Django

Django eliminates a lot of the work that would otherwise be required when working with cookies. Django offers methods like set_cookie() that make creating cookies a breeze.

These are the attributes of set_cookie():

  • name: It provides the cookie’s name.
  • value: is responsible for specifying either the variable or the text you intend to store in the cookie.
  • max_age: it describes the cookies’ duration in seconds. As a result, the cookie expires when the time expired equals the max_age. The max_age is, however, optional. So, when not set, the cookie is active as long the browser remains open.

This method is added to our view functions for cookie creation.

def addCookie(request):
  html = HttpResponse("Codeunderscored Django Cookie Tutorial")
  
  html.set_cookie('codeunderscored', ' Here is your Cookies', max_age = None)
  return html
 

Running this function ensures that it will return to the browser, and you may check the cookie created in your browser settings. Because we’re utilizing localhost, the site’s name is also localhost.

Now, add these paths to your project’s urls.py file as follows:

path('set/cookie', AddCookie),
path('get/cookie', showCookie),

It will include the required routes for calling view functions. In the following part, we will define both functions.

How to read Cookies from the request

Retrieving data from cookies is extremely trivial when using Django. First, the server receives a cookie for every given request. As a result, cookies are similarly sent for each client’s submission to the website.

Making a request

The COOKIES attribute in Django’s request object is similar to the COOKIES array in PHP. Thus, COOKIES is a request attribute whose value is the cookie’s name from which data is to be read. You can adjust this amount numerous times depending on the cookie you wish to save because there can be multiple cookies. The subsequent section elaborates on how it functions.

To access a class parameter, we’ll use the following syntax:

request.COOKIES['cookie_name']

def showCookie(request):
  show = request.COOKIES['codeunderscored']
  html = " New Page{0}".format(show)
  return HttpResponse(html)

From the current request received by the browser, this function will read the cookie named codeunderscored. We can also generate a new cookie if the values change in this function.

How the Request is put to use

COOKIES.get()

Get as a method is vital in retrieving a given value from the request body. That is the top way Django specifies fetching some given value from the cookie.

We’ll use the following syntax:

COOKIES.get('value','cookie name')

Let’s tweak our last example a little bit. For example, let us make the following changes on views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse

def addCookie(request):
  html = HttpResponse(" Codeunderscored Django Cookies Tutorial ")

if request.COOKIES.get('visits'): 
  html.set_cookie('codeunderscored', 'Welcome Back')
  value = int(request.COOKIES.get('visits'))
  html.set_cookie('visits', value + 1)
else:
  value = 1
  text = "Welcome for the first time"
  html.set_cookie('visits', value)
  html.set_cookie('codeunderscored', text)
return html

The logic establishes if cookies are contained in the request and subsequently sets the given cookies as needed. In quest to utilize COOKIES,we will use – get().

Please make the necessary changes to our showcookie() now.

def showcookie(request):
  if request.COOKIES.get('visits') is not None:
    value = request.COOKIES.get('visits')
    text = request.COOKIES.get('codeunderscored')
    html = HttpResponse(" {0} You have requested this page {1} times ".format(text, value))
	html.set_cookie('visits', int(value) + 1)
	return html
else:
  return redirect('/set/cookie')

It first confirms the presence of cookies before running it.

You can comfortably run the server, parse the value, get/cookie, on your browser’s address bar. The code checks whether the cookie contains a value and, if it doesn’t, redirects you to the addCookie function.

How to delete a cookie in Django

Django gives you simple cookie deletion methods. We used set_cookie() to generate cookies, and a similar function, delete_cookie(), can be used to remove cookies.

The delete_cookie() method is connected with the response object and takes in the cookie’s name to be erased. This function is included in your views.py file.

def delete_cookie(request):
  if request.COOKIES.get('visits'):
    response = HttpResponse(" codeunderscored Cookie deleted ")
	response.delete_cookie("visits")
  else:
    response = HttpResponse(" codeunderscored need to create cookie before deleting")
  return response

Making The request: Cookie Example in Django

Cookie values can also be obtained through the COOKIES[‘key’] array. Two functions in views.py are used to set and get cookies: addCookie() and fetchCookie().

// views.py

from django.shortcuts import render
from django.http import HttpResponse

def setcookie(request):
  response = HttpResponse("Cookie Set")
  response.set_cookie('Django-Cookie-Tutorial', 'Codeunderscored.com')
  return response

def getcookie(request):
  _article = request.COOKIES['Django-Cookie-Tutorial']
  return HttpResponse("Codeunderscored Articles @: "+ _article);

We define the URLs specified to access these functions below.

// urls.py configurations

from cookiesapp import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('s/cookie',views.addCookie),
path('g/cookie',views.fetchCookie)
]


Setting and Fetching the Cookie

Set cookie using the localhost:8000/s/cookie URL after the server has been started. The browser will receive some output as a result.

And use the localhost:8000/g/cookie URL to get a cookie. The last-mentioned informs the browser about the set cookie.

Reminders about using Cookies in Django

When utilizing cookies, keep this in mind:

  • When dealing with sensitive data, for instance, passwords, avoid using cookies. It is the nature in which cookies plainly store data. It is done such that anybody can access them without any struggle.
  • The exact quantity of cookies per website varies by browser; see Browser Cookie Limits for more information. The latter points to a limit to the data you can store in a cookie which is the majority of browsers are around 4KB per cookie. Some browsers even specify a limit of about 30 cookies at max in a given website.
  • Ideally, placing a cookie in a browser means that every request to the server has the cumulative count of the cookies present. For instance, if you have 13 cookies, each having a size of 4KB, then overall, there will be an increase by 52KB’s of data for every request made.
  • Users can delete the cookies as they so wish. In addition, users will configure their browsers to either accept or reject cookies.

Conclusion

The requirements of your application have a lot of saying. For instance, they determine whether to keep a per-site-visitor kind of data or not.

Remember that cookies are saved on the client-side, which means that the functioning of cookies is entirely dependent on the nature and level of security put in place in the client’s browser.

You should only employ cache-based sessions to utilize the Memcached cache backend. It’ll be faster to use file or database sessions directly rather than sending everything through the file or database cache backends because the local-memory cache backend doesn’t keep data long enough. Furthermore, the local-memory cache backend is not multi-process safe, making it unsuitable for production environments.

This article has covered the fundamentals of cookies and how to use them in Django. You are now ready to make your cookies and use them as much as you like using any appropriate level of Python.

When using cookies on a hosted server, such as those where the website asks for your permission to accept cookies, you will need additional awareness of the norms and legislation as a developer.

Similar Posts

Leave a Reply

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