Skip to content

Commit a3bbf47

Browse files
perf: Assistant cors config
1 parent 02e468b commit a3bbf47

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

backend/apps/system/crud/assistant.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11

22

3+
from fastapi import FastAPI
34
from sqlmodel import Session, select
45
from apps.datasource.models.datasource import CoreDatasource
56
from apps.system.models.system_model import AssistantModel
67
from apps.system.schemas.auth import CacheName, CacheNamespace
78
from apps.system.schemas.system_schema import UserInfoDTO
89
from common.core.sqlbot_cache import cache
9-
10+
from common.core.db import engine
11+
from starlette.middleware.cors import CORSMiddleware
12+
from common.core.config import settings
1013

1114
@cache(namespace=CacheNamespace.EMBEDDED_INFO, cacheName=CacheName.ASSISTANT_INFO, keyExpression="assistant_id")
1215
async def get_assistant_info(*, session: Session, assistant_id: int) -> AssistantModel | None:
@@ -23,3 +26,28 @@ def get_assistant_ds(*, session: Session, assistant: AssistantModel):
2326
# filter private ds if offline
2427
return db_ds_list
2528
pass
29+
30+
31+
def init_dynamic_cors(app: FastAPI):
32+
try:
33+
with Session(engine) as session:
34+
list_result = session.exec(select(AssistantModel).order_by(AssistantModel.create_time)).all()
35+
seen = set()
36+
unique_domains = []
37+
for item in list_result:
38+
if item.domain:
39+
for domain in item.domain.split(','):
40+
domain = domain.strip()
41+
if domain and domain not in seen:
42+
seen.add(domain)
43+
unique_domains.append(domain)
44+
cors_middleware = None
45+
for middleware in app.user_middleware:
46+
if middleware.cls == CORSMiddleware:
47+
cors_middleware = middleware
48+
break
49+
if cors_middleware:
50+
updated_origins = list(set(settings.all_cors_origins + unique_domains))
51+
cors_middleware.kwargs['allow_origins'] = updated_origins
52+
except Exception as e:
53+
return False, e

backend/main.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from starlette.middleware.cors import CORSMiddleware
77
from starlette.exceptions import HTTPException as StarletteHTTPException
88
from apps.api import api_router
9+
from apps.system.crud.assistant import init_dynamic_cors
910
from apps.system.middleware.auth import TokenMiddleware
1011
from common.core.config import settings
1112
from common.core.response_middleware import ResponseMiddleware, exception_handler
@@ -27,6 +28,7 @@ async def lifespan(app: FastAPI):
2728
run_migrations()
2829
FastAPICache.init(InMemoryBackend())
2930
print("✅ FastAPICache 初始化完成")
31+
init_dynamic_cors(app)
3032
yield
3133

3234

0 commit comments

Comments
 (0)