From 5ce97c05fe9d7c83d3469a3c809da0b9dc6632e8 Mon Sep 17 00:00:00 2001 From: Ben Firshman Date: Thu, 9 Jun 2016 18:03:32 -0700 Subject: [PATCH] Lazily connect to Redis in voting app Allows voting app to boot up without anything else. Signed-off-by: Ben Firshman --- voting-app/app.py | 13 +++++++------ voting-app/utils/__init__.py | 17 ----------------- 2 files changed, 7 insertions(+), 23 deletions(-) delete mode 100644 voting-app/utils/__init__.py diff --git a/voting-app/app.py b/voting-app/app.py index df556b5..1f1bc4e 100644 --- a/voting-app/app.py +++ b/voting-app/app.py @@ -1,8 +1,5 @@ -from flask import Flask -from flask import render_template -from flask import request -from flask import make_response -from utils import connect_to_redis +from flask import Flask, render_template, request, make_response, g +from redis import Redis import os import socket import random @@ -12,9 +9,12 @@ option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() -redis = connect_to_redis("redis") app = Flask(__name__) +def get_redis(): + if not hasattr(g, 'redis'): + g.redis = Redis(host="redis", db=0) + return g.redis @app.route("/", methods=['POST','GET']) def hello(): @@ -25,6 +25,7 @@ def hello(): vote = None if request.method == 'POST': + redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) diff --git a/voting-app/utils/__init__.py b/voting-app/utils/__init__.py deleted file mode 100644 index 6235e0f..0000000 --- a/voting-app/utils/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -import time -from redis import Redis, ConnectionError - - -def connect_to_redis(host): - time.sleep(2) - print "Connecting to redis" - - while True: - try: - redis = Redis(host=host, db=0) - redis.ping() - print "Connected to redis" - return redis - except ConnectionError: - print "Failed to connect to redis - retrying" - time.sleep(1)