11import asyncio
22import json
3+ import os
34from datetime import datetime , timezone
45from pathlib import Path
56
67from aiohttp import web
78
89
910ROOT = Path (__file__ ).resolve ().parent
10- SCORES_PATH = ROOT / "scores.json"
11+ SCORES_PATH = Path ( os . environ . get ( "PACMAN_SCORES_PATH" , ROOT / "scores.json" ))
1112STATIC_FILES = {
1213 "/" : ROOT / "index.html" ,
1314 "/index.html" : ROOT / "index.html" ,
@@ -169,11 +170,26 @@ async def post_score(request):
169170 return web .json_response ({"player" : player , "leaders" : rank_leaders (data .get ("players" , {}))})
170171
171172
173+ @web .middleware
174+ async def cors_middleware (request , handler ):
175+ if request .method == "OPTIONS" :
176+ response = web .Response (status = 204 )
177+ else :
178+ response = await handler (request )
179+ response .headers ["Access-Control-Allow-Origin" ] = "*"
180+ response .headers ["Access-Control-Allow-Methods" ] = "GET,POST,OPTIONS"
181+ response .headers ["Access-Control-Allow-Headers" ] = "Content-Type"
182+ return response
183+
184+
172185async def create_app ():
173- app = web .Application ()
186+ app = web .Application (middlewares = [ cors_middleware ] )
174187 store = ScoreStore (SCORES_PATH )
175188 await store .ensure_file ()
176189 app ["store" ] = store
190+ app .router .add_options ("/api/leaderboard" , lambda _request : web .Response (status = 204 ))
191+ app .router .add_options ("/api/player/{browserId}" , lambda _request : web .Response (status = 204 ))
192+ app .router .add_options ("/api/score" , lambda _request : web .Response (status = 204 ))
177193 app .router .add_get ("/" , serve_static )
178194 app .router .add_get ("/index.html" , serve_static )
179195 app .router .add_get ("/style.css" , serve_static )
@@ -187,5 +203,7 @@ async def create_app():
187203
188204if __name__ == "__main__" :
189205 application = asyncio .run (create_app ())
190- print ("http://localhost:8080" )
191- web .run_app (application , host = "localhost" , port = 8080 )
206+ host = os .environ .get ("HOST" , "localhost" )
207+ port = int (os .environ .get ("PORT" , "8080" ))
208+ print (f"http://{ host } :{ port } " )
209+ web .run_app (application , host = host , port = port )
0 commit comments