本文介绍了如果我在Flask应用程序中使用SimpleCache,会出现什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用以下设置:NGINX + Gunicorn + Flask。我们需要添加一点缓存,每个Flask worker不超过5Mb。 SimpleCache似乎是最简单的解决方案 - 在Python进程本身内部使用本地内存。



不幸的是,这个文档声明如下:
$ b

However, I fail to see where thread safety would matter at all in our setup. I think that Gunicorn keeps several Flask workers running, and each worker has its own small cache. What can possibly go wrong?

解决方案

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

Now, the way I can do that only once is by using a Cache to store the user`s ip and username in the cache.

Now the problem arises when each gunicorn process initializes its own cache. If add the username+ip combination for proc1's cache if proc2 picks up the next request by the same user it won't find it in its cache and hence add it to its cache and the database again, which is not suitable. Hence, a thread-safe (process-safe) cache is important in this case.

Example logs:

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]

You can see gunicorn process 14776 added it to its cache first and the next request was picked by 14776 and hence the database entry happened only once, but after that the next request got picked up by 14779 which add it to its cache and hence the db.

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

Using a memcache or redis based cache might solve it. I`m experimenting with that myself.

这篇关于如果我在Flask应用程序中使用SimpleCache,会出现什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:57