Skip to content

Instantly share code, notes, and snippets.

@hrshadhin
Last active June 24, 2020 14:16
Show Gist options
  • Save hrshadhin/0965164bfe1c35bad762c84eeed1f578 to your computer and use it in GitHub Desktop.
Save hrshadhin/0965164bfe1c35bad762c84eeed1f578 to your computer and use it in GitHub Desktop.
setup [redis](https://pypi.org/project/redis) library with flask using factory pattern or as a flask extension
# create redis extension for flask
import redis
from flask import current_app, _app_ctx_stack
class MyRedis(object):
"""Manage Redis Connection"""
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.teardown_appcontext(self.teardown)
def teardown(self, exception):
pass
def connect(self):
return redis.Redis(host=current_app.config['REDIS_HOST'], port=current_app.config['REDIS_PORT'],
db=current_app.config['REDIS_DB'])
@property
def connection(self):
ctx = _app_ctx_stack.top
if ctx is not None:
if not hasattr(ctx, 'redis_db'):
ctx.redis_db = self.connect()
return ctx.redis_db
# now use on app create / factory pattern
# Method: 1
from flask import Flask
import MyRedis
redis = MyRedis()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_object)
redis.init_app(app)
return app
# Method: 2
from flask import Flask
import MyRedis
app = Flask(__name__)
app.config.from_object(config_object)
redis = MyRedis(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment