Move high score into the class, begin sanitise etcd

This commit is contained in:
Nico Schottelius 2019-05-26 18:26:14 +02:00
parent 64a5bc57d7
commit 063da32ae9
2 changed files with 88 additions and 36 deletions

View file

@ -41,26 +41,79 @@ class Ping6(Level):
"""
class Game(object):
def __init__(self, name):
self.client = etcd.Client(port=2379)
def __init__(self, name, etcdclient, etcbase="/ungleichgame/v1"):
self.client = etcdclient
self.app = Flask(name)
self.app.add_url_rule('/', 'highscore', self.highscore)
self.app.add_url_rule('/highscore', 'highscore', self.highscore)
self.app.add_url_rule("/register", 'register', self.register, methods=['POST'])
# etcd paths are below here
self.etcbase = etcbase
self.userbase = "{}/user".format(self.etcbase)
def read_etcd(self, path, recursive=False):
try:
data = self.client.read(path, recursive=recursive)
except etcd.EtcdKeyNotFound:
return None
except Exception:
abort(Response(status=400, response="Error connecting to etcd"))
return data
def get_highscore(self, username=None):
""" Returns a dict['username'] = points """
all_users = {}
highscore = {}
print("getting high")
if username:
path = "{}/{}".format(self.userbase, username)
user = self.read_etcd(path)
if user:
all_users[username] = user
else:
path = "{}/".format(self.userbase)
users = self.read_etcd(path, recursive=True)
print("reading from {}".format(path))
if users:
for child in users.children:
print("adding user {} {} = {}".format(child, child.key, child.value))
all_users[child.key] = child.value
for k, v in all_users.items():
# Ignore all kind of errors - just add the ones that work
try:
highscore[k] = json.loads(v)['points']
print("f?")
except Exception as e:
print(e)
return highscore
def highscore(self):
return Response("A lof of points")
point_list = self.get_highscore()
res = []
if not point_list:
return Response("No winners yet!")
for k, v in point_list.items():
res.append("<p>{} has {} points</p>".format(k, v))
@app.route("/")
def high_score():
return "High score!"
return Response("\n".join(res))
@app.route("/register", methods=['POST'])
def register():
def require_args(self, *args):
parser = reqparse.RequestParser()
parser.add_argument('network', required=True)
parser.add_argument('user', required=True)
args = parser.parse_args()
for arg in args:
parser.add_argument(arg, required=True)
return parser.parse_args()
def register(self):
args = self.require_args("network", "user")
# Needs to be fixed with ungleich-otp
username=args['user']
@ -74,12 +127,13 @@ def register():
if not net.prefixlen == 64:
return Response(status=400, response="{} mask is not /64 - please use a /64 network".format(net))
client = etcd.Client(port=2379)
client.write("/ungleichgame/v1/{}/network".format(username), network)
data = client.read("/ungleichgame/v1/{}/network".format(username))
self.client.write("/ungleichgame/v1/{}/network".format(username), network)
data = self.client.read("/ungleichgame/v1/{}/network".format(username))
return json.dumps("All good, go to /level/1 to start with level 1! - {}".format(data.value))
@app.route("/level/1", methods=['GET', 'POST']) # post for username
def get_ip_address():
parser = reqparse.RequestParser()
@ -147,8 +201,7 @@ if __name__ == '__main__':
print("{} has {}".format(username, net))
g = Game(__name__)
g = Game(__name__, etcd.Client(port=2379))
g.app.run(port='5002')
app.run(port='5002')
# app.run(port='5002')

View file

@ -24,4 +24,3 @@
*** Test: is /64 ping6able?
* Features
** TODO ungleich-otp support
**