Refactor main.py, Fix model, update user.html,

This commit is contained in:
Dominic Zimmer 2020-07-17 23:43:09 +02:00
parent f0b30fdd7d
commit fe8635ea93
3 changed files with 9 additions and 78 deletions

66
main.py
View File

@ -7,50 +7,14 @@ import json
from model import Model from model import Model
routes = aiohttp.web.RouteTableDef() routes = aiohttp.web.RouteTableDef()
routes.static('/static', 'static') routes.static('/static', 'static')
admintoken = "ae33fd8cc4fdcb1ff50ba42ff48046a7"
CLIENT_REGEX = r'/{client:[a-zA-Z0-9]{16}}'
def get_client(request: aiohttp.web.Request):
client = request.match_info.get("client", None)
model = request.app['model']
if not client:
print('[get_client] client is not set, wtf')
raise aiohttp.web.HTTPBadRequest()
if not model.exists_client(client):
#print(f'[get_client] model does not know {client=}')
raise aiohttp.web.HTTPBadRequest()
return client
@routes.get(CLIENT_REGEX)
async def handler(request: aiohttp.web.Request):
# this handler prevents people missing trailing slashes
client = get_client(request)
raise aiohttp.web.HTTPFound(f"{client}/")
@routes.get(CLIENT_REGEX + '/')
async def handler(request: aiohttp.web.Request):
client = get_client(request)
#print(f"{client=} accessed")
return aiohttp.web.FileResponse('ui.html')
@routes.post('/api/token{authtoken}/{method}') @routes.post('/api/token{authtoken}/{method}')
async def handler(request: aiohttp.web.Request): async def handler(request: aiohttp.web.Request):
method = request.match_info.get('method', None) method = request.match_info.get('method', None)
token = request.match_info.get('authtoken', None) token = request.match_info.get('authtoken', None)
model = request.app['model'] model = request.app['model']
data = await request.json() data = await request.json()
try: try:
assert method in model.ApiMethod.dict assert method in model.ApiMethod.dict
value = await model.ApiMethod.dict[method](model, token, **data) value = await model.ApiMethod.dict[method](model, token, **data)
@ -59,22 +23,15 @@ async def handler(request: aiohttp.web.Request):
else: else:
return aiohttp.web.Response(status=200) return aiohttp.web.Response(status=200)
except Exception as e: except Exception as e:
del e # unused?
traceback.print_exc() traceback.print_exc()
return aiohttp.web.Response(status=400) return aiohttp.web.Response(status=400)
#finally:
# await model.send_state(client)
@routes.post('/api/{method}') @routes.post('/api/{method}')
async def handler(request: aiohttp.web.Request): async def handler(request: aiohttp.web.Request):
#client = get_client(request)
method = request.match_info.get('method', None) method = request.match_info.get('method', None)
model = request.app['model'] model = request.app['model']
data = await request.json() data = await request.json()
try: try:
assert method in model.ApiMethod.dict assert method in model.ApiMethod.dict
value = await model.ApiMethod.dict[method](model, **data) value = await model.ApiMethod.dict[method](model, **data)
@ -83,17 +40,8 @@ async def handler(request: aiohttp.web.Request):
else: else:
return aiohttp.web.Response(status=200) return aiohttp.web.Response(status=200)
except Exception as e: except Exception as e:
del e # unused?
traceback.print_exc() traceback.print_exc()
return aiohttp.web.Response(status=400) return aiohttp.web.Response(status=400)
#finally:
# await model.send_state(client)
@routes.get(f"/api/{admintoken}")
async def handler(request: aiohttp.web.Request):
model = request.app['model']
return aiohttp.web.json_response(model.model)
@routes.get('/dealer/{usertoken}') @routes.get('/dealer/{usertoken}')
async def handler(request): async def handler(request):
@ -105,28 +53,14 @@ async def handler(request):
del request # unused del request # unused
return aiohttp.web.FileResponse('index.html') return aiohttp.web.FileResponse('index.html')
@routes.get('/register/{username:.+}')
async def handler(request):
model = request.app['model']
username = request.match_info.get('username', 'Joe')
username = urllib.parse.unquote(username)
client = model.create_client(username)
raise aiohttp.web.HTTPFound(f"/{client}/")
if __name__ == '__main__': if __name__ == '__main__':
app = aiohttp.web.Application() app = aiohttp.web.Application()
app.add_routes(routes) app.add_routes(routes)
data = {} data = {}
filename = "scoreboard.json" filename = "scoreboard.json"
if os.path.isfile(filename): if os.path.isfile(filename):
with open(filename) as f: with open(filename) as f:
data = json.load(f) data = json.load(f)
app['model'] = Model(model = data) app['model'] = Model(model = data)
aiohttp.web.run_app(app, port=42042) aiohttp.web.run_app(app, port=42042)
app['model'].save() app['model'].save()

View File

@ -77,7 +77,7 @@ class Model(object):
@ApiMethod @ApiMethod
async def get_user(self, authtoken): async def get_user(self, authtoken):
user = self.verify_user(authtoken) user = self.verify_user(authtoken)
return {"user":user.name} return user.to_json()
@ApiMethod @ApiMethod
async def set_score(self, authtoken, newscore): async def set_score(self, authtoken, newscore):

View File

@ -23,6 +23,9 @@
display: flex; display: flex;
justify-content: space-around; justify-content: space-around;
} }
input {
width: 8rem;
}
</style> </style>
</head> </head>
@ -36,26 +39,20 @@
<table id="thetable"> <table id="thetable">
<tbody> <tbody>
<tr> <tr>
<td>Current Washing Coins:</td> <td>Sold Washing Coins</td>
<td id="currentcoins">42</td> <td id="currentcoins">42</td>
</tr> </tr>
<tr> <tr>
<td>Maximally Available:</td> <td>Maximum Available</td>
<td>69</td> <td id="maxcoins">69</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
<div class="biceps"> <div class="biceps">
<div> <div>
<button>Click me</button> <input type="number" value = "1" >
</div> <button id="sell">Sell</button>
<div>
<input type="number" value = "42" >
<button>Click me</button>
</div>
<div>
<button>Click me</button>
</div> </div>
</div> </div>