Python's Flask framework USES Redis for data caching configuration
- 2020-05-12 06:25:20
- OfStack
Redis is a high-performance Key-Value storage system released under the BSD open source license. It reads data into memory for efficient access. Redis is very high performance and can support more than 100K+ read/write frequency per second. It also supports features such as notification of expiration of key, so it is very suitable for caching.
Download and install
Download the package according to redis Chinese website using wget
$ wget http://download.redis.io/releases/redis-3.0.5.tar.gz
$ tar xzf redis-3.0.5.tar.gz
$ cd redis-3.0.5
$ make
The base 2 files are compiled in the src directory. Can be started with the command 1:
$ src/redis-server
This allows you to see that the redis service is up and that the default port is 6379 and reids can be operated through client.
$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"
flask configuration redis
The first step is to download flask's cache plugin, Flask-Cache, using pip.
sudo pip install flask_cache
Extend flask_cache for applications
from flask import Flask
from flask.ext.cache import Cache
cache = Cache()
config = {
'CACHE_TYPE': 'redis',
'CACHE_REDIS_HOST': '127.0.0.1',
'CACHE_REDIS_PORT': 6379,
'CACHE_REDIS_DB': '',
'CACHE_REDIS_PASSWORD': ''
}
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
@app.route('/')
@cache.cached(timeout=60*2)
def index():
name = 'mink'
return name
if __name__ == '__main__':
app.run()
Use the decorator cached() to decorate the view function and parameter timeout to set the expiration time. In this article, two minutes is used as the cache time.