Django Sessions

I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?


Asked by: Emma869 | Posted: 01-10-2021






Answer 1

The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.

The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.

If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.

Answered by: Brianna242 | Posted: 02-11-2021



Answer 2

I'm no Django expert, so this answer is about session stores generally. Downvote if I'm wrong.

Performance and Scalability

Choice of session store has an effect on performance and scalability. This should only be a big problem if you have a very popular application.

Both database and filesystem session stores are (usually) backed by disks so you can have a lot of sessions cheaply (because disks are cheap), but requests will often have to wait for the data to be read (because disks are slow). Memcached sessions use RAM, so will cost more to support the same number of concurrent sessions (because RAM is expensive), but may be faster (because RAM is fast).

Filesystem sessions are tied to the box where your application is running, so you can't load balance between multiple application servers if your site gets huge. Database and memcached sessions let you have multiple application servers talking to a shared session store.

Simplicity

Choice of session store will also impact how easy it is to deploy your site. Changing away from the default will cost some complexity. Memcached and RDBMSs both have their own complexities, but your application is probably going to be using an RDBMS anyway.

Unless you have a very popular application, simplicity should be the larger concern.

Bonus

Another approach is to store session data in cookies (all of it, not just an ID). This has the advantage that the session store automatically scales with the number of users, but it has disadvantages too. You (or your framework) need to be careful to stop users forging session data. You also need to keep each session small because the whole thing will be sent with every request.

Answered by: Daryl761 | Posted: 02-11-2021



Answer 3

As of Django 1.1 you can use the cached_db session back end.

This stores the session in the cache (only use with memcached), and writes it back to the DB. If it has fallen out of the cache, it will be read from the DB.

Although this is slower than just using memcached for storing the session, it adds persistence to the session.

For more information, see: Django Docs: Using Cached Sessions

Answered by: Darcy441 | Posted: 02-11-2021



Answer 4

One thing that has to be considered when choosing session backend is "how often session data is modified"? Even sites with moderate traffic will suffer if session data is modified on each request, making many database trips to store and retrieve data.

In my previous work we used memcache as session backend exclusively and it worked really well. Our administrative team put really great effort in making two special memcached instances stable as a rock, but after bit of twiddling with initial setup, we did not have any interrupts of session backends operations.

Answered by: Lucas176 | Posted: 02-11-2021



Answer 5

If the database have a DBA that isn't you, you may not be allowed to use a database-backed session (it being a front-end matter only). Until django supports easily merging data from several databases, so that you can have frontend-specific stuff like sessions and user-messages (the messages in django.contrib.auth are also stored in the db) in a separate db, you need to keep this in mind.

Answered by: John867 | Posted: 02-11-2021



Similar questions

python - Using sessions in Django

I'm using sessions in Django to store login user information as well as some other information. I've been reading through the Django session website and still have a few questions. From the Django website: By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to s...


python - Django, Apache and Sessions

How to ensure that session is not cleared after Apache restart( or stop and start) ? Because when I upgrade my source code and restart Apache, I refresh the web page and there I have to login again. Session is lost. Session is stored in Memcache. No idea how and why its cleared. How to preserve the session so that the user need not login after the apache restart?


python - Empty sessions in Django

I'm unable to write session keys and values to the session file using Django 1.5, Python 2.7 (64 bits), and Windows OS. I set the SESSION_ENGINE variable as django.contrib.sessions.backends.file, and the SESSION_FILE_PATH as C://Users//Doboro//My Documents//Aptana Studio 3 Workspace//test//src The session file is created with the name "sessionid3i52btehkwssb...


python - Where does Django store sessions?

I have this code in my project that assigns a unique id to an anomymous user and saves it in a session: user_id = str(uuid.uuid4())[:5] request.session['nonuserid'] = user_id Documentation says that sessions are stored in my database. I thought it would save it in


python - How to use sessions in Django

# In mypage.html <form method='get' action=''> <input type="submit" value="add" name="add"/> </form> <h1>{{ p }}</h1> # In the views.py file p = 1 def mypage(request): global p my_dictionary = { "p" : p, } if request.GET.get('add'): p = p+1 if 'p' in request.session: request.session['p'] = request.session['p'] + 1 el...


python - Django 1.7 - how to purge single user's all sessions to allow access to app only from one tab?

I want to make my app available to user from only one instance of browser (window, tab). My idea is: delete all the sessions for logging-in user so only one browser instance can be used. But how I can achieve this?


python - use sessions out of the views django

I made a Custom template tag using this doc like this in my Django application : myproject/ __init__.py models.py templatetags/ __init__.py myCustomTags.py views.py in the myCustomTags.py, I need to use some variables that...


python - Store name value with Django sessions for another view

The error that Django throws at me when I fill in the form is: 'GetSessionName' object has no attribute 'name' and I have never worked with sessions before so I don't know how to solve this problem. The idea of the site is to have a small Login screen where you type your name then move to the chat. views.py from django.shortcuts import render, redirect from django.utils import timezone from .models im...


python - Use sessions in django in order to check if someone is loged in or not

I tried to create a dictionary key in the request.session: request.session['key'] = 1232354 When a user navigate into the website, I check if they have the key in order to know if they are logged in. I'm new to Django and I am afraid that there is some big cons in this idea, like easily getting the web site hacked or something. Is there anything ...


python - Django sessions doesn't allow me to add items in my cart

I am creating an eCommerce store and I use Django sessions to store the cart information. However, for some reason, only 2 items get stored in the cart and no more. Once I add the first item, it stays there as it is. Then I add the 2nd item. However, when I add the 3rd item, the 2nd item is overwritten by the 3rd one, still keeping only 2 products in the cart. I feel it would be a simple logic error but I can't seem...


python - How to use Django sessions

I'm new to Django and i'm trying to build a Todo app with user authentication but i want to add sessions to it whereby everyone can have different tasks attached to their accounts but i don't know how to go about it. I've checked the Django documentation on it but i still don't get it. Here's my models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your ...


python - How to share memory buffer across sessions in Django?

I want to have one party (or more) sends a stream of data via HTTP request(s). Other parties will be able to receive the same stream of data in almost real-time. The data stream should be accessible across sessions (according to access control list). How can I do this in Django? If possible I would like to avoid database access and use in memory buffer (along with some synchronization mechanism)


python - Using sessions in Django

I'm using sessions in Django to store login user information as well as some other information. I've been reading through the Django session website and still have a few questions. From the Django website: By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to s...


PHP to Python Server Pages, Sessions and EXEC

I'm trying to convert this PHP to psp(python server pages). I'm at a loss with the php exec function and isset for the session variables. session_start(); if(isset($_POST["var"])){ //set session username $username = (string)$_POST["var"]; $username = trim($username); $_SESSION['username'] = $username; //store $username } if(isset($_SESSION['username'])){ $username = $_SESSION['username'...


python - How to I delete all Flask sessions?

How do I delete all sessions and cookies set by my Flask/python app. So that when users return they have to re-login. I want to do this each time I push a new version of the code to production otherwise.


python - Django, Apache and Sessions

How to ensure that session is not cleared after Apache restart( or stop and start) ? Because when I upgrade my source code and restart Apache, I refresh the web page and there I have to login again. Session is lost. Session is stored in Memcache. No idea how and why its cleared. How to preserve the session so that the user need not login after the apache restart?


python - Empty sessions in Django

I'm unable to write session keys and values to the session file using Django 1.5, Python 2.7 (64 bits), and Windows OS. I set the SESSION_ENGINE variable as django.contrib.sessions.backends.file, and the SESSION_FILE_PATH as C://Users//Doboro//My Documents//Aptana Studio 3 Workspace//test//src The session file is created with the name "sessionid3i52btehkwssb...


python - Syntax error at "def" in Django views using sessions

This is in an app in a Django project, in the views file for that app. The app is installed in settings.py, but it throws the error before it should be calling the view up. I am getting an error at the "f" in "def" at CouponForm, it says that it is a SyntaxError but I can't fing the problem. The urlconf only references the manageCoupons function. Thanks in advance for any help! views.py: fr...


python - how to use url encode for login sessions?

I have created a session for login and it gets a token from the session and goes to the same page with user method having a get request and returns a response 200. This is my code: import requests import urllib2 import urllib s=requests.Session() url = "http://www.example.com/api/2/" url1= "http://www.example.com/api/2/areas" values = { 'username': 'XXXXXXX', 'password': 'XXXXXXX', 'Conte...


python - User Sessions in an oauth2 django app

I use django, django rest framework and ember.js; my entire application thereforce communicates via ajax. Authentication is done via oauth2 and a token is send in the headers within every request. Everythings nice and shiny but file downloads. At one point users can download a pdf and I don't know how to apply authentication there - because on the file download I cannot send and headers, it's just a...


python - Where does Django store sessions?

I have this code in my project that assigns a unique id to an anomymous user and saves it in a session: user_id = str(uuid.uuid4())[:5] request.session['nonuserid'] = user_id Documentation says that sessions are stored in my database. I thought it would save it in


winapi - Shared folder sessions in Python

I'm trying to get a list of currently-open sessions in Python via WMI. What I'm after is the exact information displayed in the Computer Management thingy, when you go to System Tools -> Shared Folders -> Sessions (ie username, computer name, connected time, that sort of thing). I know (or at least believe) it has something to do with Win32_ConnectionSh...


python - How to share memory buffer across sessions in Django?

I want to have one party (or more) sends a stream of data via HTTP request(s). Other parties will be able to receive the same stream of data in almost real-time. The data stream should be accessible across sessions (according to access control list). How can I do this in Django? If possible I would like to avoid database access and use in memory buffer (along with some synchronization mechanism)


python - Using sessions in Django

I'm using sessions in Django to store login user information as well as some other information. I've been reading through the Django session website and still have a few questions. From the Django website: By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to s...


PHP to Python Server Pages, Sessions and EXEC

I'm trying to convert this PHP to psp(python server pages). I'm at a loss with the php exec function and isset for the session variables. session_start(); if(isset($_POST["var"])){ //set session username $username = (string)$_POST["var"]; $username = trim($username); $_SESSION['username'] = $username; //store $username } if(isset($_SESSION['username'])){ $username = $_SESSION['username'...


python - Doubts regarding Server side session using caching or cookie based sessions

I am pretty new to web development. I am working with Flask, Sqlalchemy and Postgresql. As far as I have understood, every new request is like a new thread of the program. New sqlalchemy session is created using which we manage our db operations and return a response. After that new thread is also closed and connections returned to the pool. I login a user and get all user data in an user orm object. I stor...


python - Is there an easy way to make sessions timeout in flask?

I'm building a website with flask where users have accounts and are able to login. I'm using flask-principal for the loging in part and the role management. Is there a way of making the user's session expire after say 5 minutes or 10 minutes? I was not able to find that in flask documentation or, flask-principal's documentation. I thought of a way of doing it by hand, set a variable server-side with a time tag at t...


python - django sessions to prevent user from multiple voting

views.py def like(request,option="food",restaurant = 1): if request.is_ajax: rest = 'rest' like = '%s-like' % str(option) if restaurant in request.session: if like not in request.session[restaurant]: request.session[restaurant][like] = str(like) else: return HttpResponse('warning') if restaurant not in request.se...


python - How to I delete all Flask sessions?

How do I delete all sessions and cookies set by my Flask/python app. So that when users return they have to re-login. I want to do this each time I push a new version of the code to production otherwise.


python - Django not storing sessions in older browsers

My application (Django 1.3) cannot seem to store session data in the following browsers: <WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{}, META:{'CSRF_COOKIE': 'dsfdfsdfsdf', 'HTTP_ACCEPT': '*/*', 'HTTP_ACCEPT_LANGUAGE': 'en-us', 'HTTP_CACHE_CONTROL': 'max-age=3600', 'HTTP_CONNECTION': 'close', 'HTTP_HOST': 'www.dxxx.com', 'HTTP_USER_AGENT': 'Mozilla/4.0 (compatible; M...


python - Django, Apache and Sessions

How to ensure that session is not cleared after Apache restart( or stop and start) ? Because when I upgrade my source code and restart Apache, I refresh the web page and there I have to login again. Session is lost. Session is stored in Memcache. No idea how and why its cleared. How to preserve the session so that the user need not login after the apache restart?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top