Merge pull request #16 from bfirsh/lazily-connect-to-redis

Lazily connect to Redis in voting app
This commit is contained in:
Ben Firshman 2016-06-10 19:31:18 +01:00 committed by GitHub
commit 6562cee08c
2 changed files with 7 additions and 23 deletions

View File

@ -1,8 +1,5 @@
from flask import Flask from flask import Flask, render_template, request, make_response, g
from flask import render_template from redis import Redis
from flask import request
from flask import make_response
from utils import connect_to_redis
import os import os
import socket import socket
import random import random
@ -12,9 +9,12 @@ option_a = os.getenv('OPTION_A', "Cats")
option_b = os.getenv('OPTION_B', "Dogs") option_b = os.getenv('OPTION_B', "Dogs")
hostname = socket.gethostname() hostname = socket.gethostname()
redis = connect_to_redis("redis")
app = Flask(__name__) 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']) @app.route("/", methods=['POST','GET'])
def hello(): def hello():
@ -25,6 +25,7 @@ def hello():
vote = None vote = None
if request.method == 'POST': if request.method == 'POST':
redis = get_redis()
vote = request.form['vote'] vote = request.form['vote']
data = json.dumps({'voter_id': voter_id, 'vote': vote}) data = json.dumps({'voter_id': voter_id, 'vote': vote})
redis.rpush('votes', data) redis.rpush('votes', data)

View File

@ -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)