cloudnet-compose/vote/app.py

46 lines
1.1 KiB
Python
Raw Normal View History

from flask import Flask, render_template, request, make_response, g
from redis import Redis
2015-11-15 20:59:29 +01:00
import os
import socket
import random
import json
option_a = os.getenv('OPTION_A', "Cats")
option_b = os.getenv('OPTION_B', "Dogs")
hostname = socket.gethostname()
app = Flask(__name__)
def get_redis():
if not hasattr(g, 'redis'):
2016-06-18 04:56:11 +02:00
g.redis = Redis(host="redis", db=0, socket_timeout=5)
return g.redis
2015-11-15 20:59:29 +01:00
@app.route("/", methods=['POST','GET'])
def hello():
voter_id = request.cookies.get('voter_id')
if not voter_id:
voter_id = hex(random.getrandbits(64))[2:-1]
vote = None
if request.method == 'POST':
redis = get_redis()
2015-11-15 20:59:29 +01:00
vote = request.form['vote']
data = json.dumps({'voter_id': voter_id, 'vote': vote})
redis.rpush('votes', data)
resp = make_response(render_template(
'index.html',
option_a=option_a,
option_b=option_b,
hostname=hostname,
vote=vote,
))
resp.set_cookie('voter_id', voter_id)
return resp
if __name__ == "__main__":
2016-06-18 00:02:54 +02:00
app.run(host='0.0.0.0', port=80, debug=True, threaded=True)