Forums

cache.get returns old data

I'm trying to do something I thought would be very simple - collecting data from a button press on a flask-generated webpage, then updating that page as a result and repeating the process (so the user data 'builds up' on the page. I think I need to use a cache to do that(?). However, my program seems to work for a while but then suddenly jumps back to an old version of the data that I put in the cache, before jumping back to the right place. There seems to be no pattern to when it jumps back. I've put some code below to illustrate the problem. So the names build up to Billxxxxxxxxxxx (11 x's) or whatever and then when I press the button it goes back to Billxxxx. Then it will go back to Billxxxxxxxxxxxx (12 x's) next time I press the button.

I know I'm probably doing something basic wrong but can't find anything that explains what I'm supposed to do! Any help much appreciated!

from flask import Flask, render_template, request
from flask_caching import Cache
app = Flask(__name__, )
app.config["DEBUG"]=True
cache = Cache(app, config={'CACHE_TYPE': 'simple','CACHE_DEFAULT_TIMEOUT': 10000000000})

@app.route('/',methods=["GET","POST"])
def test():

    if request.method=="GET":
        people=['Bill','Jim','Dave']
        cache.set('cache_people',people)
        return render_template("peoplenames.html",people=people)

    if request.method=="POST":
        people=cache.get('cache_people')
        for n in range(0,len(people)):
            people[n]=people[n]+'x'

        cache.set('cache_people',people)
        return render_template("peoplenames.html",people=people)

A simple cache like that has a separate instance for each process that serves pages for your website, so it's not a good place to keep data if you want to keep information from page visit to page visit, because each visit will go to a randomly-selected process -- so you'll see effects just like the one you describe.

The Flask technique you need to use in order to keep information from page to page is to use a "session" -- if you google "flask sessions" then you'll probably find a page that will describe it much better than I can :-)

Ah - that's solved it. Many thanks Giles!

No problem, glad to help!