What is the difference between a cookie and a session in django? What is the difference between a cookie and a session in django? django django

What is the difference between a cookie and a session in django?


A cookie is something that sits on the client's browser and is merely a reference to a Session which is, by default, stored in your database.

The cookie stores a random ID and doesn't store any data itself. The session uses the value in the cookie to determine which Session from the database belongs to the current browser.

This is very different from directly writing information on the cookie.

Example:

httpresponse.set_cookie('logged_in_status', 'True')# terrible idea: this cookie data is editable and lives on your client's computerrequest.session['logged_in_status'] = True# good idea: this data is not accessible from outside. It's in your database.


A cookie is not a Django, or Python specific technology. A cookie is a way of storing a small bit of state in your client's browser. It's used to supplement (or hack around, depending on your point of view) HTTP, which is a stateless protocol. There are all sorts of limitations here, other domains cant read your cookies, you can only store a a few k of data (just how much depends on the browser!), etc, etc.

A cookie can be used to store a session key. A session is a collection of user state that's stored server side. The session key gets passed back to the server, which allows you to look up that session's state. Most web frameworks (not just Django) will have some sort of session concept built in. This lets you add server-side state to an HTTP conversation.