A little about Session and Cookies
In this session (no pun intended), I will try to discuss the topic of HTTP sessions and cookies. Prior understanding of HTTP is assumed, but just to refresh your mind, HTTP is a protocol governing communication between a client and server using requests and responses. A client sends a request, the server receives the request, processes the request, then sends back the response to the client, and finally the client receives the response. That is the HTTP request/response cycle..
Although this post will show examples using Python (or specifically Flask microframework), the theory should generally apply to any development language/framework.
We start by understanding Session and Cookies. Session and cookies are used by different websites for sharing user's data across different pages of the site. They both track information specific to a given user of a website. A session is maintained through a global variable stored on the server side, while cookies are maintained through small files (typically maximum 4KB, but may depend on the browser) stored on the browser or client side of a web application.
By design, HTTP requests are stateless. It means that a series of HTTP requests from the same browser (client/user) appear to the server as totally independent. The server cannot tell that they are all coming from the same browser or user. Typically, web servers don't maintain any information from request to request. A web-developer, therefore, would find it difficult to bundle together a series of requests from the same client. What if each request could have an identifier which is specific to a client? The answer to this question can help us to solve this problem using sessions and cookies.
More about Session
A session is used to save information on the server temporarily so that it may be used across various pages of the web application. A session starts when the user logs in to a website, and ends when the user logs out or closes the browser. Without session, the data available on one page would not be available when the user opens another page. With session, the data is made available using the session variable, which is a global variable. Session allows you to store information specific to a user from one request to the next.
In Python, we can set a session variable (global) as a dictionary like these examples
session[‘username’] = ‘rorama’ session[‘username’] = request.form[‘username’] # read from a form request
Throughout the above session, we can access username from anywhere in the application using this
username = session.get(‘username’)
As you can see above, one must be familiar with data structures (dictionaries specifically) to be able to effectively use sessions.
It is secure to use sessions since they are stored in binary or encrypted form on the server. Each session is unique for each user (and is identified with sessionID), and an application can have unlimited number of sessions.
A simple use case of session is where we want each application user to have a custom value for number of rows that a page can display after they login. After login, we can have the user set the value for rowsPerPage in a form, and then we store it in a session variable as follows
session['rows_per_page'] = int(request.form[‘rowsPerPage’])
Then we use the following throughout the application to show pages with the defined number of rows
session.get('rows_per_page')
More about Cookies
Cookies are text files with small pieces of data, e.g. a username and password, that are used to identify your computer as you use a computer network. As already noted above, cookies are stored on the client side of a web application. When a user first visits a website, and if the site is configured to use cookies, then the server will send data to the user’s computer in the form of a cookie. All subsequent requests by the client to the server then transmit along cookie information (sessionId) in the header.
Cookie data is labeled with an ID unique to you and your computer - your Session ID. When the cookie is exchanged between your computer and the server, the server reads the ID and knows what information to specifically serve to you.
The aim of Cookies is to remember and track data that is relevant to customer usage for better visitor experience and website statistics.
A cookie expires on the lifetime set by the user.
The information stored in cookies is not safe since it is kept on the client-side in a text format that anybody could easily access, but cookies can be disabled if necessary.
In Python, to access cookies you can use the cookies attribute of the request object. To set cookies you can use the set_cookie method of response objects. The cookies attribute of the request object is a dictionary with all the cookies received from the client.
Reading cookies
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
Storing cookies
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username','rorama')
return resp For dictionaries, note that we use request.cookies.get('username') rather than request.cookies['username'] so that the code doesn't break in case request.cookies is not set.
That is it for today.
No comments:
Post a Comment