Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating flask app with Redis database. And I have one connection question

I can have Redis connection global and keep non-closed all time:

init.py

import os
from flask import Flask
import redis

app = Flask(__name__)

db = redis.StrictRedis(host='localhost', port=6379, db=0)

Also I can 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 I should use it?

Thanks for the help!

like image 943
KiraLT Avatar asked Aug 02 '13 17:08

KiraLT


1 Answers

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.

like image 124
will-hart Avatar answered Oct 14 '22 16:10

will-hart