diff --git a/api.py b/api.py index 0e04e0b..9ecc769 100644 --- a/api.py +++ b/api.py @@ -7,6 +7,8 @@ import os import time from jinja2 import Environment, FileSystemLoader import requests +import datetime as dt +import sqlite3 REGION = "euw1" @@ -29,16 +31,41 @@ def divisionToNumber(division): "IV" : 0 } return divisionmap[division] -cache = dict() -counter = +DATABASE = "rating_cache.sqlite" +def checkPlayerKnown(playerName): + conn = sqlite3.connect(DATABASE) + cursor = conn.cursor() + backlog = dt.datetime.now() - dt.timedelta(days=7) + query = '''SELECT * from players where playerName = ? LIMIT 1;''' + cursor.execute(query, (playerName,)) + try: + playerName, rating, lastUpdated = cursor.fetchone() + except TypeError: + print("sqlite cache player not found") + return None + conn.close() + return (playerName, rating, lastUpdated) -def getCache(): - return cache +def addToDB(playerName, rating): + + conn = sqlite3.connect(DATABASE) + cursor = conn.cursor() + cursor.execute("INSERT INTO players VALUES(?,?,?);",( + playerName, + rating, + dt.datetime.now().timestamp())) + conn.commit() + conn.close() + def getPlayerRatingFromApi(playerName, WATCHER): - if playerName in cache: - return cache[playerName] + if not playerName: + return 0 + + tupel = checkPlayerKnown(playerName) + if tupel: + return tupel[1] while(True): try: @@ -46,7 +73,7 @@ def getPlayerRatingFromApi(playerName, WATCHER): except requests.exceptions.HTTPError as e: # not found # if e.response.status_code == 404: - cache[playerName] = 0 + addToDB(playerName, 0) return 0 # rate limit elif e.response.status_code == 429: @@ -56,7 +83,7 @@ def getPlayerRatingFromApi(playerName, WATCHER): else: raise e if not pTmp: - cache[playerName] = 0 + addToDB(playerName, 0) return 0 computed = 0 @@ -77,6 +104,6 @@ def getPlayerRatingFromApi(playerName, WATCHER): computed = tierToNumber(queue["tier"]) + divisionToNumber(queue["rank"]) + \ int(queue["leaguePoints"]) print(computed) - cache.update( { playerName : computed }) + addToDB(playerName, computed) return computed diff --git a/server.py b/server.py index 3e9c830..08a9a3b 100755 --- a/server.py +++ b/server.py @@ -152,7 +152,7 @@ class Player: submission = dict() @app.route("/role-submission", methods=['GET', 'POST']) def roleSubmissionTool(): - positions=["Top", "Jungle", "Mid", "Support", "Bottom"] + positions=["Top", "Jungle", "Mid", "Bottom", "Support" ] ident = flask.request.args.get("id") if flask.request.method == 'POST': @@ -192,11 +192,12 @@ def balanceToolData(): return flask.Response(json.dumps(retDict), 200, mimetype='application/json') +@app.route('/') @app.route("/balance-tool", methods=['GET', 'POST']) def balanceTool(): - positions=["Top", "Jungle", "Mid", "Support", "Bottom"] + positions=["Top", "Jungle", "Mid", "Bottom", "Support"] - db = DatabaseConnection(app.config["DB_PATH"]) + #db = DatabaseConnection(app.config["DB_PATH"]) if flask.request.method == 'POST': @@ -310,6 +311,14 @@ def playerApi(): else: return ("Nope", 404) +@app.route("/player-api-cache") +def playerApiCache(): + result = api.checkPlayerKnown(flask.request.args.get("id")) + if result: + return ("OK", 200) + else: + return ("Nope", 404) + @app.route("/player") def player(): '''Show Info about Player''' @@ -366,7 +375,6 @@ def player(): Y_MIN=yMin, Y_MAX=yMax) @app.route('/leaderboard') -@app.route('/') @cache.cached(timeout=10, query_string=True) def leaderboard(): '''Show main leaderboard page with range dependant on parameters''' @@ -452,12 +460,6 @@ def send_js(path): @app.before_first_request def init(): - SERVERS_FILE = "servers.json" - if os.path.isfile(SERVERS_FILE): - import valve.source.a2s - from valve.source import NoResponseError - with open(SERVERS_FILE) as f: - SERVERS = json.load(f) global WATCHER with open("key.txt","r") as f: @@ -472,7 +474,7 @@ if __name__ == "__main__": parser.add_argument('--port', default="5002", \ help='Port on which flask (this server) will take requests on') - parser.add_argument('--skillbird-db', required=True, help='skillbird database (overrides web connection if set)') + parser.add_argument('--skillbird-db', required=False, help='skillbird database (overrides web connection if set)') args = parser.parse_args() diff --git a/sqlite.init b/sqlite.init new file mode 100644 index 0000000..d56cfc3 --- /dev/null +++ b/sqlite.init @@ -0,0 +1,5 @@ +CREATE TABLE players( + playerName TEXT PRIMARY KEY, + rating INTEGER, + lastupdated TEXT +); diff --git a/static/balance.js b/static/balance.js index 54a2331..06bef43 100644 --- a/static/balance.js +++ b/static/balance.js @@ -1,4 +1,4 @@ -positions = [ "Top", "Jungle", "Mid", "Support" , "Bottom" ] +positions = [ "Top", "Jungle", "Mid", "Bottom", "Support" ] acceptedParser = [ "top", "jungle", "mid", "sup" , "bot", "adc", "support", "bottom", "*" ] sides = [ "left", "right"] @@ -6,7 +6,7 @@ var checkPlayerFunc = function checkPlayer() { if(this.value == ""){ return } - url = "/player?id=" + this.value + url = "/player-api-cache?id=" + this.value fetch(url).then(r => { if(r.status == 200){ this.style.background = "#74bb74"