Last active
June 24, 2020 14:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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