title: How to cache SQL Alchemy calls with Flask-Cache and Redis?
body: <p>I have a Flask app that takes parameters from a web form, queries a DB with SQL Alchemy and returns Jinja-generated HTML showing a table with the results. I want to cache the calls to the DB. I looked into Redis (<a href="https://stackoverflow.com/questions/24583263/using-redis-as-an-lru-cache-for-postgres">Using redis as an LRU cache for postgres</a>), which led me to <a href="http://pythonhosted.org/Flask-Cache/" rel="noreferrer">http://pythonhosted.org/Flask-Cache/</a>.</p>
  
  <p>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 set up a custom Redis cache.  </p>
  
  <pre><code>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)
  </code></pre>
  
  <p>From there I would need to something like:</p>
  
  <pre><code># not sure what to put for args or kwargs
  cache = redis(app, config={'CACHE_TYPE': 'redis'})
  
  app = Flask(__name__)
  cache.init_app(app)
  </code></pre>
  
  <p>I have two questions: </p>
  
  <ol>
  <li><p>What do I put for <code>args</code> and <code>kwargs</code>? What do these mean? How do I set up a Redis cache with Flask-Cache?</p></li>
  <li><p>Once the cache is set up, it seems like I would want to somehow "<a href="http://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.memoize" rel="noreferrer">memoize</a>" the calls 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:</p>
  
  <pre><code>@cache.memoize(timeout=50)
  def queryDB(q):
      return q.all()
  </code></pre></li>
  </ol>
  
  <p>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.</p>