waliullah123 commited on
Commit
e6414cc
Β·
verified Β·
1 Parent(s): df61bba

fix: use starlette middleware to intercept /backend/ requests before Gradio routing

Browse files
Files changed (1) hide show
  1. app.py +45 -36
app.py CHANGED
@@ -718,46 +718,55 @@ try:
718
  description="Backend API for Fake News Detection. REST API available at /backend/api/*"
719
  )
720
 
721
- # ── 3. FastAPI proxy: /backend/{path} β†’ Flask on 127.0.0.1:7861/{path} ──
722
  _SKIP_HEADERS = {'host', 'content-length', 'transfer-encoding', 'content-encoding'}
723
 
724
- @demo.app.api_route(
725
- "/backend/{path:path}",
726
- methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"]
727
- )
728
- async def flask_proxy(request: _FastAPIRequest, path: str):
729
- """Transparent proxy forwarding /backend/* β†’ internal Flask server."""
730
- target_url = f"http://127.0.0.1:{_FLASK_PORT}/{path}"
731
- fwd_headers = {
732
- k: v for k, v in request.headers.items()
733
- if k.lower() not in _SKIP_HEADERS
734
- }
735
- try:
736
- async with httpx.AsyncClient(timeout=60) as client:
737
- resp = await client.request(
738
- method=request.method,
739
- url=target_url,
740
- headers=fwd_headers,
741
- content=await request.body(),
742
- params=dict(request.query_params),
743
- follow_redirects=True,
744
- )
745
- resp_headers = {
746
- k: v for k, v in resp.headers.items()
747
  if k.lower() not in _SKIP_HEADERS
748
  }
749
- return _FastAPIResponse(
750
- content=resp.content,
751
- status_code=resp.status_code,
752
- headers=resp_headers,
753
- )
754
- except Exception as proxy_err:
755
- logger.error(f"Proxy error for /{path}: {proxy_err}")
756
- return _FastAPIResponse(
757
- content=b'{"error":"Backend proxy error","detail":"' + str(proxy_err).encode() + b'"}',
758
- status_code=502,
759
- headers={"Content-Type": "application/json"},
760
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
761
 
762
  _GRADIO_AVAILABLE = True
763
 
 
718
  description="Backend API for Fake News Detection. REST API available at /backend/api/*"
719
  )
720
 
721
+ # ── 3. FastAPI middleware proxy: /backend/{path} β†’ Flask on 127.0.0.1:7861/{path} ──
722
  _SKIP_HEADERS = {'host', 'content-length', 'transfer-encoding', 'content-encoding'}
723
 
724
+ @demo.app.middleware("http")
725
+ async def flask_proxy_middleware(request: _FastAPIRequest, call_next):
726
+ if request.url.path.startswith("/backend/"):
727
+ target_path = request.url.path[len("/backend"):]
728
+ if not target_path.startswith("/"):
729
+ target_path = "/" + target_path
730
+
731
+ target_url = f"http://127.0.0.1:{_FLASK_PORT}{target_path}"
732
+
733
+ # Read the request body
734
+ body = await request.body()
735
+
736
+ fwd_headers = {
737
+ k: v for k, v in request.headers.items()
 
 
 
 
 
 
 
 
 
738
  if k.lower() not in _SKIP_HEADERS
739
  }
740
+
741
+ try:
742
+ async with httpx.AsyncClient(timeout=60) as client:
743
+ resp = await client.request(
744
+ method=request.method,
745
+ url=target_url,
746
+ headers=fwd_headers,
747
+ content=body,
748
+ params=dict(request.query_params),
749
+ follow_redirects=True,
750
+ )
751
+ resp_headers = {
752
+ k: v for k, v in resp.headers.items()
753
+ if k.lower() not in _SKIP_HEADERS
754
+ }
755
+ return _FastAPIResponse(
756
+ content=resp.content,
757
+ status_code=resp.status_code,
758
+ headers=resp_headers,
759
+ )
760
+ except Exception as proxy_err:
761
+ logger.error(f"Proxy error for {request.url.path}: {proxy_err}")
762
+ return _FastAPIResponse(
763
+ content=b'{"error":"Backend proxy error","detail":"' + str(proxy_err).encode() + b'"}',
764
+ status_code=502,
765
+ headers={"Content-Type": "application/json"},
766
+ )
767
+
768
+ # If not /backend/*, let Gradio handle it normally
769
+ return await call_next(request)
770
 
771
  _GRADIO_AVAILABLE = True
772