jbilcke-hf HF Staff commited on
Commit
525b397
·
1 Parent(s): b8eae92
Files changed (1) hide show
  1. server.py +19 -6
server.py CHANGED
@@ -576,12 +576,24 @@ async def init_app(base_path="") -> web.Application:
576
 
577
  # Add routes with CORS headers for WebSockets
578
  # Configure CORS for all routes
 
579
  async def cors_middleware(request, handler):
580
- response = await handler(request)
581
- response.headers['Access-Control-Allow-Origin'] = '*'
582
- response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
583
- response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'
584
- return response
 
 
 
 
 
 
 
 
 
 
 
585
 
586
  app.middlewares.append(cors_middleware)
587
 
@@ -614,5 +626,6 @@ def parse_args() -> argparse.Namespace:
614
 
615
  if __name__ == '__main__':
616
  args = parse_args()
617
- app = asyncio.run(init_app(base_path=args.path))
 
618
  web.run_app(app, host=args.host, port=args.port)
 
576
 
577
  # Add routes with CORS headers for WebSockets
578
  # Configure CORS for all routes
579
+ @web.middleware
580
  async def cors_middleware(request, handler):
581
+ if request.method == 'OPTIONS':
582
+ # Handle preflight requests
583
+ resp = web.Response()
584
+ resp.headers['Access-Control-Allow-Origin'] = '*'
585
+ resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
586
+ resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'
587
+ return resp
588
+
589
+ # Normal request, call the handler
590
+ resp = await handler(request)
591
+
592
+ # Add CORS headers to the response
593
+ resp.headers['Access-Control-Allow-Origin'] = '*'
594
+ resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
595
+ resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'
596
+ return resp
597
 
598
  app.middlewares.append(cors_middleware)
599
 
 
626
 
627
  if __name__ == '__main__':
628
  args = parse_args()
629
+ loop = asyncio.get_event_loop()
630
+ app = loop.run_until_complete(init_app(base_path=args.path))
631
  web.run_app(app, host=args.host, port=args.port)