如何使用flas -cache和redis缓存sql炼金术调用?

时间:2022-09-18 20:29:35

I have a flask app that takes parameters from a web form, queries a DB w/ SQL alchemy and returns a jinja-generated template showing a table with the results. I want to cache the calls to the DB. I looked into redis, Using redis as an LRU cache for postgres -- which lead me to http://pythonhosted.org/Flask-Cache/

我有一个flask应用程序,它从web表单获取参数,查询一个DB w/ SQL alchemy,并返回一个jinja生成的模板,该模板显示一个包含结果的表。我想缓存对DB的调用。我查看了redis,使用redis作为postgres的LRU缓存——它引导我访问http://pythonhosted.org/Flask-Cache/。

Now I am trying to use redis + flask-cache to cache the calls to the DB. Based on the Flask-Cache docs it seems like I need to setup a custom redis cache.

现在我尝试使用redis + flas -cache来缓存对DB的调用。基于flas - cache文档,我似乎需要设置一个自定义的redis缓存。

class RedisCache(BaseCache):
    def __init__(self, servers, default_timeout=500):
        pass

def redis(app, config, args, kwargs):
   args.append(app.config['REDIS_SERVERS'])
   return RedisCache(*args, **kwargs)

From there I would need to something like

从那以后,我需要一些类似的东西

cache = redis(app, config={'CACHE_TYPE': 'redis'}) //not sure what to put for args or kwards?

app = Flask(__name__)
cache.init_app(app)

I have two questions:

我有两个问题:

First: what do I put for args and kwargs? What do these mean? How do I setup a redis cache with flask cache?

首先:我对args和kwargs有什么看法?这些是什么意思?如何设置带有flask缓存的redis缓存?

Second: once the cache is set up it seems like I would want to somehow "memoize" the calls the the DB so that if the method gets the same query it has the output cached. How do I do this? My best guess would be to wrap the call the SQL alchemy in a method that could then be given memoize decorator? That way if two identical queries were passed to the method, flask-cache would recognize this and return to the appropriate response. I'm guessing that it would look like this:

第二:设置好缓存后,我似乎想以某种方式“记忆”调用DB,以便如果方法得到相同的查询,它就会缓存输出。我该怎么做呢?我的最佳猜测是将调用SQL炼金术包装在一个方法中,然后可以给它一个memoize decorator?这样,如果将两个相同的查询传递给该方法,flask-cache将识别该查询并返回到相应的响应。我猜它应该是这样的:

@cache.memoize(timeout=50)
def queryDB(q):
    return q.all()

This seems like a fairly common use of redis + flask + flask-cache + sql alchemy but I am unable to find a complete example to follow. If someone could post one, that would be super helpful -- but for me and for others down the line.

这似乎是redis + flask + flask-cache + sql炼金术的一种常见用法,但我无法找到一个完整的示例。如果有人能发表一篇文章,那将会非常有帮助——但对我和其他人来说都是如此。

2 个解决方案

#1


31  

You don't need to create custom RedisCache class. The docs is just teaching how you would create new backends that are not available in flask-cache. But RedisCache is already available in werkzeug >= 0.7, which you might have already installed because it is one of the core dependencies of flask.

您不需要创建自定义的RedisCache类。文档只是告诉您如何创建在flask-cache中不可用的新后端。但是RedisCache已经在werkzeug >= 0.7中可用,您可能已经安装了它,因为它是flask的核心依赖项之一。

This is how I could run the flask-cache with redis backend:

这就是我如何使用redis后端运行flask-cache:

import time
from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

@cache.memoize(timeout=60)
def query_db():
    time.sleep(5)
    return "Results from DB"

@app.route('/')
def index():
    return query_db()

app.run(debug=True)

The reason you're getting "ImportError: redis is not a valid FlaskCache backend" is probably because you don't have redis (python library) installed which you can simply install by:
pip install redis.

您获得“ImportError: redis不是一个有效的FlaskCache后端”的原因可能是因为您没有安装redis (python库),您可以通过:pip install redis简单地安装它。

#2


12  

your redis args would look something like this:

你的红色args会是这样的:

cache = Cache(app, config={
    'CACHE_TYPE': 'redis',
    'CACHE_KEY_PREFIX': 'fcache',
    'CACHE_REDIS_HOST': 'localhost',
    'CACHE_REDIS_PORT': '6379',
    'CACHE_REDIS_URL': 'redis://localhost:6379'
    })

Putting the @cache.memoize over a method that grabs the info from the DB should work.

把@cache。对于从数据库中获取信息的方法的memoize应该起作用。

#1


31  

You don't need to create custom RedisCache class. The docs is just teaching how you would create new backends that are not available in flask-cache. But RedisCache is already available in werkzeug >= 0.7, which you might have already installed because it is one of the core dependencies of flask.

您不需要创建自定义的RedisCache类。文档只是告诉您如何创建在flask-cache中不可用的新后端。但是RedisCache已经在werkzeug >= 0.7中可用,您可能已经安装了它,因为它是flask的核心依赖项之一。

This is how I could run the flask-cache with redis backend:

这就是我如何使用redis后端运行flask-cache:

import time
from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

@cache.memoize(timeout=60)
def query_db():
    time.sleep(5)
    return "Results from DB"

@app.route('/')
def index():
    return query_db()

app.run(debug=True)

The reason you're getting "ImportError: redis is not a valid FlaskCache backend" is probably because you don't have redis (python library) installed which you can simply install by:
pip install redis.

您获得“ImportError: redis不是一个有效的FlaskCache后端”的原因可能是因为您没有安装redis (python库),您可以通过:pip install redis简单地安装它。

#2


12  

your redis args would look something like this:

你的红色args会是这样的:

cache = Cache(app, config={
    'CACHE_TYPE': 'redis',
    'CACHE_KEY_PREFIX': 'fcache',
    'CACHE_REDIS_HOST': 'localhost',
    'CACHE_REDIS_PORT': '6379',
    'CACHE_REDIS_URL': 'redis://localhost:6379'
    })

Putting the @cache.memoize over a method that grabs the info from the DB should work.

把@cache。对于从数据库中获取信息的方法的memoize应该起作用。