redis缓存 flask
时间: 2023-12-02 12:43:04 浏览: 170
flask redis
在Flask中使用Redis缓存可以通过flask-redis插件来实现。下面是使用flask-redis实现Redis缓存的步骤:
1.安装flask-redis插件
```shell
pip install flask-redis
```
2.在Flask应用程序中配置Redis
```python
from flask import Flask
from flask_redis import FlaskRedis
app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
redis_store = FlaskRedis(app)
```
3.使用Redis缓存数据
```python
from flask import Flask
from flask_redis import FlaskRedis
app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
redis_store = FlaskRedis(app)
@app.route('/')
def index():
# 设置缓存
redis_store.set('name', 'Tom')
# 获取缓存
name = redis_store.get('name')
return name
```
4.使用Redis缓存视图函数的返回值
```python
from flask import Flask
from flask_redis import FlaskRedis
from flask_caching import Cache
app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
redis_store = FlaskRedis(app)
cache = Cache(app, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': 'redis://localhost:6379/0'})
@app.route('/')
@cache.cached(timeout=60)
def index():
return 'Hello World!'
```
阅读全文