Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Session and Cookie

Flask Session and Cookie

The HTTP protocol itself is stateless—the server does not automatically remember whether two requests come from the same user.

Flask solves this problem through the Session mechanism, allowing web applications to "remember" a user's state.


How Session works

Flask uses SecureCookieSession by default, which works as follows:

Users can see the cookie's content (because it is base64-encoded) but cannot tamper with it—any modification causes signature verification to fail.

How Session-Signed Cookies Work


Configuring SECRET_KEY

To use Session, you must first set SECRET_KEY—the key used for signing.

Example

import

secrets

from

flask

import

Flask

app

=

Flask

(

name

)

Generate a secure random key (only needed on first run)

secrets.token_hex() produces a 64-character hexadecimal random string

app.

secret_key

=

secrets.

token_hex

(

)

Or set a fixed value directly (convenient for development, but do not use in production)

app.secret_key = "dev-secret-key-change-in-production"

Important:SECRET_KEY It must be kept secret and sufficiently random. If the key leaks, anyone can forge your application's Session data. In production, read it from environment variables or a configuration file, and do not hardcode it in the code.

Command to generate a high-quality secret key:



$ python -c 'import secrets; print(secrets.token_hex())'

192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf


Reading and writing Session

session is a dict-like object, used basically the same way as a Python dict:

Example

from

flask

import

Flask

,

session

,

redirect

,

url_for

,

request

app

=

Flask

(

name

)

app.

secret_key

=

"dev-secret-key"

@

app.

route

(

"/"

)

def

index

(

)

:

   

Check whether username is in the session

   

if

"username"

in

session:

       

return

f

"""
       

Welcome back, {session["username"]}!


       

Your number of visits: {session.get("visits", 0)}


       

Log out


        """

   

return

"""
   

RUNOOB homepage


   

You are not logged in.


   

Go to login


    """

@

app.

route

(

"/login"

,

methods

=

[

"GET"

,

"POST"

]

)

def

login

(

)

:

   

if

request.

method

==

"POST"

:

        username

=

request.

form

.

get

(

"username"

,

""

)

       

if

username:

           

Store the username in the session

            session

[

"username"

]

=

username

           

Initialize the visit count

            session

[

"visits"

]

=

0

           

return

redirect

(

url_for

(

"index"

)

)

   

return

"""
   


       

Log in to RUNOOB


       


       


   

    """

@

app.

route

(

"/logout"

)

def

logout

(

)

:

   

Clear all data in the session

    session.

clear

(

)

   

Or delete only a specific key:

   

session.pop("username", None)

   

return

redirect

(

url_for

(

"index"

)

)


Permanent Session

By default, Session expires when the browser closes (browser session level).

If you need a "remember me" feature, you can mark the Session as permanent:

Example

from

datetime

import

timedelta

Set the validity period of the permanent session (default 31 days)

app.

config

[

"PERMANENT_SESSION_LIFETIME"

]

=

timedelta

(

days

=

7

)

@

app.

post

(

"/login-remember"

)

def

login_remember

(

)

:

    username

=

request.

form

.

get

(

"username"

)

   

if

username:

        session

[

"username"

]

=

username

       

Mark as a permanent session, still valid after the browser closes

        session.

permanent

=

True

       

return

redirect

(

url_for

(

"index"

)

)


Message Flashing—one-time messages

After a user submits a form, feedback such as "operation successful" or "error" needs to be displayed.

For such "show once and disappear" messages, Flask provides the flash() mechanism.

Example

from

flask

import

Flask

,

flash

,

get_flashed_messages

,

redirect

,

render_template

,

request

,

url_for

app

=

Flask

(

name

)

app.

secret_key

=

"dev-secret-key"

@

app.

route

(

"/post"

,

methods

=

[

"GET"

,

"POST"

]

)

def

create_post

(

)

:

   

if

request.

method

==

"POST"

:

        title

=

request.

form

.

get

(

"title"

,

""

)

.

strip

(

)

       

if

not

title:

           

Save an error message to flash with category "error"

            flash

(

"Title cannot be empty"

,

"error"

)

           

return

redirect

(

url_for

(

"create_post"

)

)

       

Save a success message to flash with category "success"

        flash

(

f

"Article '{title}' published successfully!"

,

"success"

)

       

return

redirect

(

url_for

(

"create_post"

)

)

   

return

render_template

(

"create_post.html"

)

@

app.

route

(

"/flash-demo"

)

def

flash_demo

(

)

:

   

Get all flashed messages (automatically cleared after reading)

    messages

=

get_flashed_messages

(

with_categories

=

True

)

   

return

render_template

(

"flash_demo.html"

,

messages

=

messages

)

Render flash messages in the template:

Example

   

<p>Publish Article - RUNOOB</p>

   

   

Publish Article

   

    {% with messages = get_flashed_messages(with_categories=true) %}

        {% if messages %}

            {% for category, message in messages %}

               

{{ message }}

            {% endfor %}

        {% endif %}

    {% endwith %}

   

       

Title:

       

   

Classification Recommended usage scenarios
"message" (default) General notification
"success" Operation successful
"error" Operation failed
"warning" Warning message
"info" General information

Flash messages depend on Session, so you must set SECRET_KEY before you can use them.


Common Session issues

Cookie size limit: Browsers limit the size of a single cookie to about 4KB. Do not store large amounts of data in Session—it is suitable for lightweight information such as user IDs and preferences, not for files or large objects.