/
app.py
executable file
·61 lines (55 loc) · 2.44 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from flask import Flask
from flask import render_template
from flask import request
from flask import make_response
from redis import Redis, RedisError
import os
import socket
import logging
import signal
import sys
optionA = "Perros"
optionB = "Gatos"
name = optionA + " VS " + optionB
redis = Redis(host="redis", db=0)
app = Flask(__name__)
@app.route("/", methods=['POST','GET'])
def hello():
try:
votesB = redis.get(optionB) or 0
votesA = redis.get(optionA) or 0
except RedisError:
votesB = "<i>cannot connect to Redis, counter disabled</i>"
votesA = "<i>cannot connect to Redis, counter disabled</i>"
if request.method == 'POST':
if request.form['option'] == 'optionA':
try:
votesA = redis.incr(optionA)
if int(votesB) > 0 and 'optionB' == request.cookies.get('vote'):
votesB = redis.decr(optionB);
redis.publish('pubsub', '{"'+optionA+'":'+str(votesA)+', "'+optionB+'":'+str(votesB)+'}')
except Exception as e:
print e
votesA = "<i>An error occured</i>"
resp = make_response(render_template('index.html', name=os.getenv('NAME', name), hostname=socket.gethostname(), optionA=optionA, optionB=optionB))
resp.set_cookie('vote', 'optionA')
return resp
if request.form['option'] == 'optionB':
try:
votesB = redis.incr(optionB)
if int(votesA) > 0 and 'optionA' == request.cookies.get('vote'):
votesA = redis.decr(optionA);
redis.publish('pubsub', '{"'+optionA+'":'+str(votesA)+', "'+optionB+'":'+str(votesB)+'}')
except Exception as e:
print e
votesB = "<i>An error occured</i>"
resp = make_response(render_template('index.html', name=os.getenv('NAME', name), hostname=socket.gethostname(), optionA=optionA, optionB=optionB))
resp.set_cookie('vote', 'optionB')
return resp
else:
return render_template('index.html', name=os.getenv('NAME', name), hostname=socket.gethostname(), optionA=optionA, optionB=optionB)
elif request.method == 'GET':
return render_template('index.html', name=os.getenv('NAME', name), hostname=socket.gethostname(), optionA=optionA, optionB=optionB)
if __name__ == "__main__":
signal.signal(signal.SIGTERM, sys.exit)
app.run(host='0.0.0.0', port=80)