2

I'm a newbie on Python and I'm trying to convert an ASP.NET application to Python to allow myself to understand Python.

I've chosen FLASK as the framework for the Python application.

Now, in .NET I've relied on sessions to identify a customer, however, this doesn't seem to work in Python - Flask.

This is my code:

@APP.errorhandler(404)
def notFound(error):
    if (session.get("demo") == None):
        session["demo"] = "value"
        return "This is a new session."
    else:
        return "This is an existing session."

if __name__ == "__main__":
    APP.secret_key = APP.config["FLASK_SECRET_KEY"]
    APP.run(debug = APP.config["FLASK_DEBUG_MODE_ENABLED"])

However, when I open a single browser window and browse to the route, I get This is a new session.

When I open another browser window, and load the route, I get This is an existing session.

How is that possible? Shouldn't a session be unique per user? Thanks in advance for any clarification.

davidism
  • 121,510
  • 29
  • 395
  • 339
Complexity
  • 5,682
  • 6
  • 41
  • 84
  • You should use a new private window, flask saves sessions in a cookie which is shared among window – oz123 Mar 09 '18 at 08:17

1 Answers1

4

This is only loosely related to Python, but more on HTTP sessions. HTTP was originaly designed as a non connected protocol. It was aimed at sending requests to various servers and collect elements. The need for tracking clients to allow flows of related requests was addressed by cookies. That's the reason why nowadays most of session implementations rely on cookies.

The problems is that browsers normally share cookies among all of their windows. So it a session is cookie based, different windows of same browser will share it however it was established: that's what you are experiencing. In that case, you need to use different browsers to have different sessions from same client machine.

But sessions can also be based on URL rewriting. Instead of being transported in a cookie, the session id it passed as a request parameter. I used to be more common in old days where many users disabled cookies, but as you can now hardly consult a website with disabled cookies, it is seldom used. But it does allow a single browser to have different sessions to the same server in different windows. Unfortunately,I do not know whether it is supported by flask.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252