Categories
Python Answers

How to share data between requests with Python Flask?

Spread the love

Sometimes, we want to share data between requests with Python Flask.

In this article, we’ll look at how to share data between requests with Python Flask.

How to share data between requests with Python Flask?

To share data between requests with Python Flask, we can store data in a session.

For instance, we write

from flask import Flask, session
from flask_session import Session

app = Flask(__name__)

SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)

@app.route('/')
def reset():
    session["counter"]=0

    return "counter was reset"

@app.route('/inc')
def routeA():
    if not "counter" in session:
        session["counter"]=0

    session["counter"]+=1

    return "counter is {}".format(session["counter"])

to create a session with Session(app).

Then we can store session data in the session dictionary.

We set session["counter"] to 0 in the reset route function.

And then we try to get the counter value in the if statement and set it if it doesn’t exist in routeA.

Conclusion

To share data between requests with Python Flask, we can store data in a session.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *