3

I'd like to set a cache variable from a background process in Flask using its SimpleCahce framework. That is:

from rq import Queue
from worker import conn
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()

app = Flask(__name__)
q = Queue(connection=conn)

# background process to be run. located in a seperate file
def test():
    for i in range(10):
        cache.set("value", i, 3600)
        time.sleep(1)

@app.route('/')
def home():
    cache.clear()
    q.empty()
    q.enqueue(test, timeout=1000)
    return jsonify({'state':"running"})

@app.route('/current_value')
def get_value():
    return jsonify({'value':cache.get("value")})

However, this will always return null. I've done this before using Redis, but is setting cache in a background process not allowed with SimpleCache? Or am I just doing something wrong?

1 Answer 1

1

Werkzeug's SimpleCache isn't thread safe. It's not intended to be used by other threads or processes as it doesn't implement locking.

Also, the documentation seems to allude to the cache being stored in process memory, which would make it quite difficult to alter the main process's cache from a secondary one.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know a recommended (and simple) caching method that is thread safe?
If you're going to need to modify the cache from multiple processes, you should use a dedicated cache server like Redis, it will save you a lot of headaches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.