When we log in to a website, with our username and password, we’re not prompted to log in again for each page we visit after, usually until we explicitly log out.
It turns out that there is another web technology called cookies, small pieces of data that a website can ask a browser to store on a user’s computer. Then, when the browser visits that website again, it will automatically send that cookie back, like a virtual handstamp that identifies ourself to the server, without having to enter our login information again. The cookie might store a long random string, to prevent adversaries from easily guessing it, and the server will remember that it corresponds to our account.
When we visit a site like Gmail for the first time, our browser will send HTTP headers like this:
GET / HTTP/1.1
Host: gmail.com
...
Then, Gmail’s server will reply with the login page. After we successfully log in, Gmail’s server will then reply with headers like this:
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session=value
...
Set-Cookie
header asks our browser to save the session
and value
key-value pair to our computer; value
will be a long random string or number that identifies us to the server.When we visit Gmail again later, our browser will send the same value back as part of the Cookie
header:
GET / HTTP/1.1
Host: gmail.com
Cookie: session=value
...
In today’s source code directory in the CS50 IDE, we’ll first look at the example called store
. We’ll cd
into the store
directory, and call flask run
in our terminal to start our IDE’s web server. Then, we can visit the link to see a simple “store”:
With cookies, we can implement sessions on our server. A session is an abstraction of saved state for each user’s visit to our website; our server might give me a cookie with session=12345
and you a cookie with session=78910
, and store some data for each user who visits, based on that session value.
With Flask, we only need a few lines of code to use this abstraction:
...
from flask_session import Session
...
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
...
@app.route("/update", methods=["POST"])
def update():
for item in request.form:
session[item] = int(request.form.get(item))
return redirect("/cart")
session
dictionary, which we can store data in our server’s memory or filesystem for each specific user.