Skip to content

Commit 7d5ebcf

Browse files
author
calderbuild
committed
fix(analytics): read BAIDU_TONGJI_ID per-request instead of at import time
The Jinja2 global was set once at module import time via templates.env.globals, which captured an empty string if the env var wasn't available during import. Changed to pass baidu_tongji_id through template context at request time, matching how the /api/config/analytics endpoint works.
1 parent 7becc5b commit 7d5ebcf

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

api/routers/seo_pages.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@
1717

1818
router = APIRouter()
1919
templates = Jinja2Templates(directory="templates")
20-
templates.env.globals["baidu_tongji_id"] = os.getenv("BAIDU_TONGJI_ID", "")
2120
limiter = Limiter(key_func=get_remote_address)
2221

2322

23+
def _common_context() -> dict:
24+
"""每次请求时动态读取的公共模板变量."""
25+
return {"baidu_tongji_id": os.getenv("BAIDU_TONGJI_ID", "")}
26+
27+
2428
@lru_cache(maxsize=128)
2529
def load_cities() -> List[Dict]:
2630
"""加载城市数据, 如不存在则创建默认值."""
@@ -94,6 +98,7 @@ async def homepage(request: Request):
9498
"schema_jsonld": schema_list,
9599
"breadcrumbs": [],
96100
"cities": load_cities(),
101+
**_common_context(),
97102
},
98103
)
99104

@@ -145,6 +150,7 @@ async def city_page(request: Request, city_slug: str):
145150
],
146151
"city": city,
147152
"city_content": city_content,
153+
**_common_context(),
148154
},
149155
)
150156

@@ -178,6 +184,7 @@ async def about_page(request: Request):
178184
{"name": "首页", "url": "/"},
179185
{"name": "关于我们", "url": "/about"},
180186
],
187+
**_common_context(),
181188
},
182189
)
183190

@@ -245,6 +252,7 @@ async def how_it_works(request: Request):
245252
{"name": "首页", "url": "/"},
246253
{"name": "使用指南", "url": "/how-it-works"},
247254
],
255+
**_common_context(),
248256
},
249257
)
250258

@@ -331,6 +339,7 @@ async def faq_page(request: Request):
331339
{"name": "常见问题", "url": "/faq"},
332340
],
333341
"faqs": faqs,
342+
**_common_context(),
334343
},
335344
)
336345

0 commit comments

Comments
 (0)