make site faster by generating html server-side

This commit is contained in:
Elijah Steres 2021-01-01 03:32:47 -05:00
parent 9c92afedc2
commit 01c73a06eb
3 changed files with 104 additions and 73 deletions

View File

@ -1,4 +1,4 @@
import asyncio, time, datetime, games, json, threading
import asyncio, time, datetime, games, json, threading, jinja2
from flask import Flask, url_for, Response, render_template, request, jsonify
from flask_socketio import SocketIO, emit
@ -10,24 +10,36 @@ socketio = SocketIO(app)
def index():
return render_template("index.html")
@app.route("/gotoboop")
def get_game_states():
return states_to_send
@socketio.on("recieved")
def handle_new_conn(data):
socketio.emit("states_update", last_update, room=request.sid)
thread2 = threading.Thread(target=socketio.run,args=(app,))
thread2.start()
master_games_dic = {} #key timestamp : (game game, {} state)
last_update = {}
game_states = {}
def data_to_send():
template = jinja2.Environment(loader=jinja2.FileSystemLoader('templates')).get_template('game.html')
data = []
for timestamp in game_states:
data.append({
'timestamp' : timestamp,
'league' : game_states[timestamp]['leagueoruser'] if game_states[timestamp]['is_league'] else '',
'html' : template.render(
state=game_states[timestamp],
base_filled="/static/img/base_filled.png",
base_empty="/static/img/base_empty.png",
out_out="/static/img/out_out.png",
out_in="/static/img/out_in.png"
)
})
return data
@socketio.on("recieved")
def handle_new_conn(data):
socketio.emit("states_update", data_to_send(), room=request.sid)
def update_loop():
while True:
states_to_send = {}
global game_states
game_times = iter(master_games_dic.copy().keys())
for game_time in game_times:
this_game, state, discrim_string = master_games_dic[game_time]
@ -110,7 +122,7 @@ def update_loop():
state["top_of_inning"] = this_game.top_of_inning
states_to_send[game_time] = state
game_states[game_time] = state
if state["update_pause"] <= 1 and state["start_delay"] < 0:
if this_game.over:
@ -123,8 +135,5 @@ def update_loop():
state["update_pause"] -= 1
global last_update
last_update = states_to_send
socketio.emit("states_update", states_to_send)
socketio.emit("states_update", data_to_send())
time.sleep(6)

View File

@ -12,11 +12,12 @@ $(document).ready(function (){
lastupdate = json;
updateGames(json, $('#selected_filter').text());
console.log(json)
//get all leagues
leagues = []
for (var key in json) {
if (json[key].is_league) {
leagues.push(json[key].leagueoruser)
for (var i in json) {
if (json[i].league != "" && !leagues.includes(json[i].league)) {
leagues.push(json[i].league)
}
}
@ -32,8 +33,8 @@ $(document).ready(function (){
})
// add leagues not already present
for (var league in leagues) { // we removed the entries that are already there in the loop above
$('#filters').append("<button class='filter'>"+leagues[league]+"</button>");
for (var i in leagues) { // we removed the entries that are already there in the loop above
$('#filters').append("<button class='filter'>"+leagues[i]+"</button>");
}
//add click handlers to each filter
@ -50,14 +51,16 @@ $(document).ready(function (){
});
const updateGames = (json, filter) => {
filterjson = Object();
for (const timestamp in json) {
if (json[timestamp].leagueoruser == filter || filter == "All") {
filterjson[timestamp] = json[timestamp];
filterjson = [];
for (var i in json) {
if (json[i].league == filter || filter == "All") {
filterjson.push(json[i]);
}
}
if (Object.keys(filterjson).length == 0) {
console.log(filterjson);
if (filterjson.length == 0) {
$('#footer div').html("No games right now. Why not head over to Discord and start one?");
} else {
$('#footer div').html("");
@ -65,16 +68,16 @@ $(document).ready(function (){
//replace games that have ended with empty slots
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
if (grid.children[slotnum].className == "game" && !Object.keys(filterjson).includes(grid.children[slotnum].timestamp)) {
if (grid.children[slotnum].className == "game" && !filterjson.some((x) => x.timestamp == grid.children[slotnum].timestamp)) {
grid.children[slotnum].className = "emptyslot";
grid.children[slotnum].timestamp = null;
grid.children[slotnum].innerHTML = "";
}
}
for (const timestamp in filterjson) {
for (var i in filterjson) {
//adds game to list if not there already
if (!Array.prototype.slice.call(grid.children).some((x) => x.timestamp == timestamp)) {
if (!Array.prototype.slice.call(grid.children).some((x) => x.timestamp == filterjson[i].timestamp)) {
for (var slotnum = 0; true; slotnum++) { //this is really a while loop but shh don't tell anyone
if (slotnum >= grid.children.length) {
for (var i = 0; i < 3; i ++) {
@ -82,7 +85,7 @@ $(document).ready(function (){
}
}
if (grid.children[slotnum].className == "emptyslot") {
insertGame(slotnum, filterjson[timestamp], timestamp);
insertGame(slotnum, filterjson[i]);
break;
};
};
@ -90,8 +93,8 @@ $(document).ready(function (){
//updates game in list
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
if (grid.children[slotnum].timestamp == timestamp) {
updateGame(grid.children[slotnum], filterjson[timestamp]);
if (grid.children[slotnum].timestamp == filterjson[i].timestamp) {
insertGame(slotnum, filterjson[i]);
};
};
};
@ -113,48 +116,10 @@ $(document).ready(function (){
grid.appendChild(newBox);
}
const insertGame = (gridboxnum, gamestate, timestamp) => {
const insertGame = (gridboxnum, game) => {
var thisBox = grid.children[gridboxnum];
thisBox.innerHTML = game.html;
thisBox.className = "game";
thisBox.timestamp = timestamp;
fetch("/static/game.html").then(x=>x.text()).then(gamehtml => {
thisBox.innerHTML = gamehtml;
updateGame(thisBox, gamestate);
});
};
const BASE_EMPTY = "/static/img/base_empty.png"
const BASE_FILLED = "/static/img/base_filled.png"
const OUT_OUT = "/static/img/out_out.png"
const OUT_IN = "/static/img/out_in.png"
const updateGame = (gamediv, gamestate) => {
gamediv.id = "updateTarget";
$('#updateTarget .inning').html("Inning: " + (gamestate.display_top_of_inning ? "🔼" : "🔽") + " " + gamestate.display_inning + "/" + gamestate.max_innings);
$('#updateTarget .weather').html(gamestate.weather_emoji + " " + gamestate.weather_text);
$('#updateTarget .away_name').html(gamestate.away_name);
$('#updateTarget .home_name').html(gamestate.home_name);
$('#updateTarget .away_score').html("" + gamestate.away_score);
$('#updateTarget .home_score').html("" + gamestate.home_score);
for (var i = 1; i <= 3; i++) {
$('#updateTarget .base_' + i).attr('src', (gamestate.bases[i] == null ? BASE_EMPTY : BASE_FILLED));
}
$('#updateTarget .outs_count').children().each(function(index) {
$(this).attr('src', index < gamestate.outs ? OUT_OUT : OUT_IN);
});
$('#updateTarget .pitcher_name').html(gamestate.pitcher);
$('#updateTarget .batter_name').html(gamestate.batter);
$('#updateTarget .update_emoji').html(gamestate.update_emoji);
$('#updateTarget .update_text').html(gamestate.update_text);
$('#updateTarget .batting').html((gamestate.display_top_of_inning ? gamestate.away_name : gamestate.home_name) + " batting.");
$('#updateTarget .leagueoruser').html(gamestate.leagueoruser);
gamediv.id = "";
thisBox.timestamp = game.timestamp;
};
});

57
templates/game.html Normal file
View File

@ -0,0 +1,57 @@
{% macro base(number) -%}
{% if state.bases[number] %}{{base_filled}}{% else %}{{base_empty}}{% endif %}
{%- endmacro %}
{% macro out(number) -%}
{% if number <= state.outs %}{{out_filled}}{% else %}{{out_empty}}{% endif %}
{%- endmacro %}
<div class="header">
<div class="inning">Inning: {% if state.display_top_of_inning == true %}🔼{% else %}🔽{% endif %} {{ state.display_inning }}/{{ state.max_innings }}</div>
<div class="weather">{{ state.weather_emoji }} {{ state.weather_text }}</div>
</div>
<div class="body">
<div class="teams">
<div class="team">
<div class="team_name">{{ state.away_name }}</div>
<div class="score">{{ state.away_score }}</div>
</div>
<div class="team">
<div class="team_name">{{ state.home_name }}</div>
<div class="score">{{ state.home_score }}</div>
</div>
</div>
<div class="info">
<div class="field">
<img class="base base_2" src="{{ base(2) }}"/>
<div style="display: flex;">
<img class="base base_3" src="{{ base(3) }}"/>
<img class="base base_1" src="{{ base(1) }}"/>
</div>
</div>
<div class="outs">
<div class="outs_title">OUTS</div>
<div class="outs_count">
<img class="out" src="{{ out(1) }}"/>
<img class="out" src="{{ out(2) }}"/>
</div>
</div>
</div>
<div class="players">
<div class="player pitcher">
<div class="player_type">Pitcher:</div>
<div class="player_name pitcher_name">{{ state.pitcher }}</div>
</div>
<div class="player batter">
<div class="player_type">Batter:</div>
<div class="player_name batter_name">{{ state.batter }}</div>
</div>
</div>
<div class="update">
<div class="update_emoji">{{ state.update_emoji }}</div>
<div class="update_text">{{ state.update_text }}</div>
</div>
</div>
<div class="footer">
<div class="batting">{% if state.display_top_of_inning == true %}{{ state.away_name }}{% else %}{{ state.home_name }}{% endif %}</div>
<div class="leagueoruser">{{ state.leagueoruser }}</div>
</div>