-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (79 loc) · 2.65 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
from flask import Flask, abort, jsonify
from markupsafe import escape
from dotenv import load_dotenv
from sqlalchemy import create_engine, MetaData, desc
from sqlalchemy.orm import sessionmaker
from model import Server, User, Beatmap, Play
app = Flask(__name__)
load_dotenv()
# Database connection
online = False
try:
db_host = os.getenv('db_host')
db_user = os.getenv('db_user')
db_password = os.getenv('db_password')
db_database = os.getenv('db_database')
DATABSE_URI=f'mysql+mysqlconnector://{db_user}:{db_password}@{db_host}/{db_database}'
engine = create_engine(DATABSE_URI)
connection = engine.connect()
metadata = MetaData()
online = True
except:
pass
@app.route("/ping", methods=['GET'])
def ping():
return "pong"
@app.route("/status", methods=['GET'])
def status():
if online:
return {"online": True}
else:
return {"online": False}
@app.route("/servers", methods=['GET'])
def servers():
SessionFactory = sessionmaker(engine)
with SessionFactory() as session:
res = []
try:
servers = session.query(Server).all()
for server in servers:
players = len(session.query(User).filter_by(server_id=server.id).all())
plays = len(session.query(Play).filter_by(server_id=server.id).all())
beatmaps = len(session.query(Beatmap).filter_by(server_id=server.id).all())
res.append({
"id": server.id,
"name": server.name,
"players": players,
"plays": plays,
"beatmaps": beatmaps,
})
except:
return {"error": ":("}
finally:
session.close()
return jsonify(res)
@app.route("/servers/<server_id>", methods=['GET'])
def server(server_id):
SessionFactory = sessionmaker(engine)
with SessionFactory() as session:
try:
server = session.query(Server).filter_by(id=server_id).all()
if len(server) != 1:
raise Exception("Invalid id")
server = server[0]
players = len(session.query(User).filter_by(server_id=server.id).all())
plays = len(session.query(Play).filter_by(server_id=server.id).all())
beatmaps = len(session.query(Beatmap).filter_by(server_id=server.id).all())
except:
return {"error": ":("}
else:
res = {
"name": server.name,
"players": players,
"plays": plays,
"beatmaps": beatmaps,
}
return res
finally:
session.close()