Implement API magic
This commit is contained in:
parent
125ecfd437
commit
7824ca8c33
6
main.py
6
main.py
@ -40,9 +40,10 @@ async def handler(request: aiohttp.web.Request):
|
||||
return aiohttp.web.FileResponse('ui.html')
|
||||
|
||||
|
||||
@routes.post(CLIENT_REGEX + '/api')
|
||||
@routes.post(CLIENT_REGEX + '/api/{method}')
|
||||
async def handler(request: aiohttp.web.Request):
|
||||
client = get_client(request)
|
||||
method = request.match_info.get('method', None)
|
||||
model = request.app['model']
|
||||
|
||||
data = await request.json()
|
||||
@ -50,7 +51,8 @@ async def handler(request: aiohttp.web.Request):
|
||||
print(f'{client=} {data=}')
|
||||
|
||||
try:
|
||||
assert await model.handle_post(client, data)
|
||||
assert method in model.ApiMethod.dict
|
||||
await model.ApiMethod.dict[method](model, client, **data)
|
||||
return aiohttp.web.Response(status=200)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
25
model.py
25
model.py
@ -13,15 +13,14 @@ def generate_random_id(_s=set()):
|
||||
|
||||
|
||||
class Model(object):
|
||||
class ApiMethod:
|
||||
dict = dict()
|
||||
|
||||
global api_methods
|
||||
api_methods = {}
|
||||
def __init__(self, fun):
|
||||
self.dict[fun.__name__] = fun
|
||||
|
||||
def api_method():
|
||||
global api_methods
|
||||
def wrapper(fun):
|
||||
api_methods[fun.__name__] = fun
|
||||
return wrapper
|
||||
def __contains__(self, item):
|
||||
return item in self.dict
|
||||
|
||||
def __init__(self, filename="tehmodel.json"):
|
||||
self.sockets = {} # mapping: client -> socket
|
||||
@ -43,13 +42,21 @@ class Model(object):
|
||||
if not "sessions" in self.model:
|
||||
self.model["sessions"] = {}
|
||||
|
||||
@api_method()
|
||||
@ApiMethod
|
||||
async def test_api(self, clientid):
|
||||
print(f'test_api {clientid=}')
|
||||
|
||||
@ApiMethod
|
||||
async def test_yeet(self, clientid):
|
||||
raise Exception('yeet')
|
||||
|
||||
@ApiMethod
|
||||
async def create_session(self, clientid) -> str:
|
||||
sessionname = generate_random_id()
|
||||
newsession = {"id": sessionname, "owner": clientid, "clients": []}
|
||||
self.model["sessions"][sessionname] = newsession
|
||||
|
||||
@api_method()
|
||||
@ApiMethod
|
||||
async def join_session(self, clientid, sessionid):
|
||||
if sessionid in self.model["sessions"]:
|
||||
self.model["sessions"][sessionid].append(clientid)
|
||||
|
Loading…
Reference in New Issue
Block a user