Skip to content

Commit

Permalink
Redis to store games
Browse files Browse the repository at this point in the history
  • Loading branch information
evrardjp committed Sep 3, 2020
1 parent c3a8fed commit 8f45739
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 10 deletions.
2 changes: 1 addition & 1 deletion constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
PROFILE_KEY = 'profile'
SECRET_KEY = 'ThisIsTheSecretKey'
JWT_PAYLOAD = 'jwt_payload'

REDIS_URL = 'REDIS_URL'
20 changes: 20 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
version: '3'

services:
redis:
image: redis:alpine
container_name: redis
restart: always
# for local dev, expose ports
ports:
- 6379:6379
# webapp:
# image: stunning-happiness:latest
# container_name: stunning-happiness
# restart: always
# environment:
# AUTH0_CLIENT_ID: ${AUTH0_CLIENT_ID}
# AUTH0_DOMAIN: ${AUTH0_DOMAIN}
# AUTH0_CLIENT_SECRET: ${AUTH0_CLIENT_SECRET}
# AUTH0_CALLBACK_URL: ${AUTH0_CALLBACK_URL}

20 changes: 20 additions & 0 deletions games.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import pickle

class Party(object):
def __init__(self, name, playername):
self.party_name = name
self.players = set(playername)
self.game_over = False
self.currently_playing = playername

def add_player(self, playername):
self.players.add(playername)

def del_player(self, playername):
self.players.discard(playername)

def close_game(self):
self.game_over = True

def pickle(self):
return pickle.dumps(self)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ python-dotenv
requests
authlib>=0.14.1
Flask-WTF
redis
35 changes: 30 additions & 5 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
from flask import url_for
from authlib.integrations.flask_client import OAuth
from urllib.parse import urlencode
from redis import from_url as redis_connection
import pickle

import forms
import constants
import games

ENV_FILE = find_dotenv()
if ENV_FILE:
Expand All @@ -32,11 +35,23 @@
AUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN)
AUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN
AUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE)
REDIS_URL = env.get(constants.REDIS_URL)

app = Flask(__name__, static_url_path='/public', static_folder='./public')
app.secret_key = constants.SECRET_KEY
app.debug = True

def redis_conn():
conn = getattr(g,'_redis', None)
if conn is None:
conn = g._redis = redis_connection(REDIS_URL)
return conn

@app.teardown_appcontext
def close_connection(exception):
conn = getattr(g, '_redis', None)
if conn is not None:
conn.close()

@app.errorhandler(Exception)
def handle_auth_error(ex):
Expand Down Expand Up @@ -116,15 +131,28 @@ def dashboard():
def newParty():
form = forms.NewGame(request.form)
if request.method == 'POST' and form.validate():
flash("A new game (named %s) has been created. Please join manually." % form.gamename.data)
games = { "name": form.gamename.data, "active_players": [ session[constants.JWT_PAYLOAD]['nickname'] ]}
# everything is stored in bytes in redis
gamename = form.gamename.data.encode()
# check if that name already exists in db before going further.
if (existing_party := redis_conn().get(gamename)) is not None:
if pickle.loads(existing_party).game_over:
flash("Re-creating a game (named %s). Click now on the right game to join the game." % form.gamename.data)
else:
flash("A game named %s already exists. Redirecting you to join page...." % form.gamename.data)
return redirect('/party/join')
else:
flash("Creating a game (named %s). Please join manually." % form.gamename.data)
party = games.Party(gamename, session[constants.JWT_PAYLOAD]['nickname'])
# pickle is (most likely?) safe, as we can assume github nicknames are going through validations
redis_conn().set(gamename, party.pickle())
return redirect('/party/join')
return render_template('new-party.html', userinfo_pretty=session[constants.JWT_PAYLOAD], form=form)


@app.route('/party/join', methods=['GET', 'POST'])
@requires_auth
def joinParty():
# redis_conn().get()
return render_template('list-party.html', games="games")


Expand All @@ -134,8 +162,5 @@ def newGame():
return render_template('new-game.html', userinfo_pretty=json.dumps(session[constants.JWT_PAYLOAD]))





if __name__ == "__main__":
app.run(host='0.0.0.0', port=env.get('PORT', 3000))
2 changes: 1 addition & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<img class="pure-img-responsive" style="max-height:18px" src="{{ session['profile']['picture']}}"/>
</li>
<li class="pure-menu-item">
<span>{{ session['profile']['name'] }}</span>
<a href="{{ url_for('dashboard') }}">{{ session['profile']['name'] }}</a>
</li>
<li class="pure-menu-item">
<a class="pure-button pure-button-primary" id="qsLogoutBtn" href="/logout">Log Out</a>
Expand Down
29 changes: 26 additions & 3 deletions templates/list-party.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,32 @@ <h1>{% block title %}List open games{% endblock %}</h1>
{% block content %}
<div class="container">
<div class="">
<div class="">
{{ games }}
</div>
<table>
<tr>
<th>
Game name
</th>
<th>
Players
</th>
<th>
Join?
</th>
</tr>
{% for game in games %}
<tr>
<td>
{{ game.name }}
</td>
<td>
{{ game.players }}
</td>
<td>
{{ game.join_link }}
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
{% endblock %}

0 comments on commit 8f45739

Please sign in to comment.