Monday, 6 September 2021

Flask-Caching use UWSGI cache with NGINX

The UWSGI is connected to the flask app per UNIX-Socket:

NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP

I have initalized a uwsgi cache to handle global data. I want to handle the cache with python package flask-caching.

I am trying to init the Cache-instance with the correct cache address. There seems to be something wrong. I think, that the parameters for app.run() are not relevant for uwsgi.

If I am setting a cache entry, it return always None:

app.route("/")
def test():
    cache.set("test", "OK", timeout=0)
    a = cache.get("test")
    return a

main.py

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
# Check Configuring Flask-Caching section for more details
cache = Cache(app, config={'CACHE_TYPE': 'uwsgi', 'CACHE_UWSGI_NAME':'mycache@localhost'})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

uwsgi.ini

[uwsgi]
module = main
callable = app
cache2 = name=mycache,items=100

nginx.conf

server {
    listen 80;
    location / {
        try_files $uri @app;
    }
    location @app {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
    location /static {
        alias /app/testapp/static;
    }
}

I am working with the docker build from https://github.com/tiangolo/uwsgi-nginx-flask-docker. The app is working, expect the cache.

Edit

After long time, I found the solution:

Be aware of using of spawning multiple processes for NGINX. Every process handles its own cache. Without an additional layer, it is not possible to access to a cache from different nginx process



from Flask-Caching use UWSGI cache with NGINX

No comments:

Post a Comment