What could go wrong if I use SimpleCache in my Flask application

We use the following setting: NGINX + Gunicorn + Flask. We need to add only a little caching, not more than 5 MB for each employee. SimpleCache is apparently the easiest solution - it uses memory locally, inside the Python process itself.

Unfortunately, the documentation states the following:

"A simple memory cache for individual processes. This class exists primarily for the development server and is not a 100% reliable thread."

However, I do not see how thread safety will matter in our setup. I think Gunicorn holds several workers in a flask, and each worker has his own small cache. What could go wrong?

+4
source share
1 answer

I am currently dealing with a scenario in which, after a user logs in to the application, I want to insert his IP address into the database.

Now the only way I can do this is to use the cache to store the ip address and username in the cache.

Now the problem arises when each firing process initializes its own cache. If you add the username + ip combination for the proc1 cache, if proc2 picks up the next request of the same user, he will not find it in his cache and, therefore, will add it to his cache and database again, which does not work. Therefore, cache protection (process safe) is important in this case.

Log examples:

2015-07-07 22:42:31 - myapp.views:29 - DEBUG - not from cache user1100.100.100.100, <type 'unicode'> [14776]
2015-07-07 22:42:31 - myapp.views:30 - DEBUG - from cache : user1100.100.100.100, <type 'unicode'> [14776]
2015-07-07 22:42:40 - myapp.views:29 - DEBUG - not from cache user1100.100.100.100, <type 'unicode'> [14776]
2015-07-07 22:42:40 - myapp.views:30 - DEBUG - from cache : user1100.100.100.100, <type 'unicode'> [14776]
2015-07-07 22:42:41 - myapp.views:29 - DEBUG - not from cache user1100.100.100.100, <type 'unicode'> [14779]
2015-07-07 22:42:41 - myapp.views:30 - DEBUG - from cache : None, <type 'NoneType'> [14779]
2015-07-07 22:42:41 - myapp.views:32 - DEBUG - new username ip [14779]
2015-07-07 22:42:41 - myapp.views:38 - DEBUG - User : user1, ip : 100.100.100.100, noted at time : Tue Jul  7 22:42:41 2015, login_count : None [14779]

, 14776 , 14776, , , , 14779, , db.

cache = SimpleCache(threshold=1000, default_timeout=3600)

memcache redis . .

+2

All Articles