HelloSun commited on
Commit
633f62a
·
verified ·
1 Parent(s): 40010af

relay:加 CORS(網頁在 aichatv,跨網域要預檢)

Browse files
Files changed (1) hide show
  1. relay.py +25 -0
relay.py CHANGED
@@ -41,12 +41,37 @@ import time
41
  from pathlib import Path
42
 
43
  from fastapi import APIRouter, Header, HTTPException, Query, Request
 
44
  from fastapi.responses import JSONResponse
45
 
46
  router = APIRouter(prefix="/api/aichat", tags=["aichat"])
47
 
48
  VERSION = 2
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # ---------------------------------------------------------------- 設定
51
  DB_PATH = Path(os.environ.get("AICHAT_DB", "/home/user/data/aichat_relay.db"))
52
  SHARED_TOKEN = os.environ.get("AICHAT_TOKEN", "").strip()
 
41
  from pathlib import Path
42
 
43
  from fastapi import APIRouter, Header, HTTPException, Query, Request
44
+ from fastapi.middleware.cors import CORSMiddleware
45
  from fastapi.responses import JSONResponse
46
 
47
  router = APIRouter(prefix="/api/aichat", tags=["aichat"])
48
 
49
  VERSION = 2
50
 
51
+ # ---------------------------------------------------------------- CORS
52
+ # 網頁在 aichatv(static Space)、中繼在 testzerogpu2,兩者不同 host → 瀏覽器一定
53
+ # 會先送 OPTIONS 預檢。這裡放行指定來源,**不是**萬用 *(萬用 * 不能帶
54
+ # Authorization 標頭,實際等於不能用)。
55
+ ALLOW_ORIGINS = [
56
+ o.strip() for o in os.environ.get(
57
+ "AICHAT_ORIGINS",
58
+ "https://hellosun-aichatv.static.hf.space,"
59
+ "https://huggingface.co,"
60
+ "http://localhost:8000,http://127.0.0.1:8000"
61
+ ).split(",") if o.strip()
62
+ ]
63
+
64
+
65
+ def install_cors(app) -> None:
66
+ app.add_middleware(
67
+ CORSMiddleware,
68
+ allow_origins=ALLOW_ORIGINS,
69
+ allow_credentials=False,
70
+ allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
71
+ allow_headers=["Authorization", "Content-Type", "X-Aichat-Token"],
72
+ max_age=600,
73
+ )
74
+
75
  # ---------------------------------------------------------------- 設定
76
  DB_PATH = Path(os.environ.get("AICHAT_DB", "/home/user/data/aichat_relay.db"))
77
  SHARED_TOKEN = os.environ.get("AICHAT_TOKEN", "").strip()