1

I'm trying to use a cookie to remember if a visitor has already seen a particular tutorial page on my site. The site is build using Flask.

The tutorial page gets loaded from flask routing so I thought it made sense to try and alter the cookie in the flask routing definition using the make_response and response.set_cookie function from the flask framework.

However, this (session) cookie is only for the duration of the session. I can't find any info on setting permanent/persistent cookies with flask. How can I do this with flask ?

Thanks!

joost2076
  • 101
  • 2
  • 8
  • Take a look at `flask-login`. It provides [remember be](https://flask-login.readthedocs.io/en/latest/#remember-me) functionality. You can also find an example of using it in Miguel Gringerg's [flask tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins) – vrs Jul 11 '16 at 11:22
  • thanks for pointing me in the right direction. Flask-login does however feel a bit like overkill just to add a property to a cookie. No other ways to change the persistent cookie? – joost2076 Jul 11 '16 at 11:56
  • 1
    can [this thread](https://stackoverflow.com/questions/11783025/is-there-an-easy-way-to-make-sessions-timeout-in-flask) be helpful? Also, make sure you use `session.permanent` properly (see [this thread](https://stackoverflow.com/questions/18662558/flask-login-session-times-out-too-soon)) – vrs Jul 11 '16 at 12:19
  • thanks again for the pointers. Much appreciated. Looked at it, tried it, but in the end just used javascript to make he cookie.... – joost2076 Jul 11 '16 at 15:43

1 Answers1

8

To set a persistent cookie, you must add the "expires" field in the http header:

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

If you don't provide Expires=, then the browser considers the cookie as a "session" cookie and deletes the cookie when the browser is closed.

For Flask, you can use the parameter expires= of the response.set_cookie() function like this for a 30-days cookie:

import datetime
response.set_cookie(name, value,
                    expires=datetime.datetime.now() + datetime.timedelta(days=30)) 
Vincent J
  • 4,968
  • 4
  • 40
  • 50