0

I'm confused about cookies in relation to Flask sessions (hereinafter "sessions"). I do understand how sessions rely on client-side cookies. My question is when we create/change/pop the value of a session variable, does that automatically create/set a cookie on the user's browser OR do I need to also explicitly manage a cookie to go with that session variable?

        session.permanent = True
        session["t_id_user"] = t_id_user
        # Is the following code needed?
        C = make_response("")
        cookie_expires = datetime.now() + timedelta(days=30)
        C.set_cookie("t_id_user", str(t_id_user), expires=cookie_expires)

Thank you!

ScotterMonkey
  • 1,007
  • 12
  • 25

1 Answers1

1

If you use the builtin and default Flask session implementation, any modifications to the Session object will automatically result in a Set-Cookie header in the response of the request that made the change.

So, you only need this code:

session.permanent = True
session["t_id_user"] = t_id_user

The rest is automatic and handled for you. And in fact more secure. If you set SECRET_KEY, the session cookie will be signed (not encrypted) such that it can't be tampered with outside of the server environment.

Diego Borba
  • 1,282
  • 8
  • 22
David K. Hess
  • 16,632
  • 2
  • 49
  • 73