Python Redis connection should be closed on every request? (flask) Python Redis connection should be closed on every request? (flask) database database

Python Redis connection should be closed on every request? (flask)


By default redis-py uses connection pooling. The github wiki says:

Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. By default, each Redis instance you create will in turn create its own connection pool.

This means that for most applications and assuming your redis server is on the same computer as your flask app, its unlikely that "opening a connection" for each request is going to cause any performance issues. The creator of Redis Py has suggested this approach:

a. create a global redis client instance and have your code use that.
b. create a global connection pool and pass that to various redis instances throughout your code.

Additionally, if you have a lot of instructions to execute at any one time then it may be worth having a look at pipelining as this reduces that back and forth time required for each instruction.


Using Flask, global variables are not recommended. We can use g to manage redis client during a request. Like manage a database connection using factory pattern.

from flask import gimport redisdef get_redis():    if 'db' not in g:        g.db = redis.Redis(host='localhost', port=6379, db=0)    return g.db

Reconnect every request is better for you.

The application context is a good place to store common data during a request or CLI command. Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context.