Should Python Redis connection be closed on every request? (Flask)

I am creating a flash application with a Redis database. And I have one connection question

I can connect Redis globally and not close all the time:

INIT .py

import os from flask import Flask import redis app = Flask(__name__) db = redis.StrictRedis(host='localhost', port=6379, db=0) 

I can also reconnect every request (Flask doc http://flask.pocoo.org/docs/tutorial/dbcon/ ):

INIT .py

 import os from flask import Flask import redis app = Flask(__name__) #code... @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() 

Which method is better? Why should I use it?

Thanks for the help!

+7
python database flask redis
source share
1 answer

By default, redis-py uses a connection pool. github wiki says:

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

This means that for most applications and assuming that your redis server is on the same computer as your flash application, it is unlikely that β€œopening a connection” for each request will cause any performance problems. The creator of Redis Py suggested this approach :

but. create a global redis client instance and use your code.
b. create a global connection pool and pass this to the various redis instances in your code.

In addition, if you have many instructions to execute at any time, it might be worth taking a look at pipelining , as this reduces the time needed for each instruction.

+16
source share

All Articles