重构板块资金流向:行业/概念改用独立 path,后端排序,前端不缓存直接请求

This commit is contained in:
Sakurasan
2026-07-13 23:22:09 +08:00
parent 94d84a368f
commit eea2ce86d0
3 changed files with 111 additions and 59 deletions
+56 -23
View File
@@ -1,4 +1,8 @@
"""板块数据路由:行业板块、概念板块""" """板块数据路由:行业板块、概念板块
注意:行业/概念必须走不同 path/industry、/concept),不能仅靠 query 参数区分。
上游反代/CDN 可能按 path 缓存并忽略 query,导致两个 tab 返回相同数据。
"""
from fastapi import APIRouter, Query, HTTPException from fastapi import APIRouter, Query, HTTPException
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@@ -6,34 +10,63 @@ from services import eastmoney, mootdx
router = APIRouter() router = APIRouter()
# 行业/概念通过 query 参数区分,但上游反代/CDN 可能按 path 缓存而忽略 query, # 禁止任何中间层缓存,确保每次请求都打到后端
# 导致两个 tab 返回相同数据。显式禁止缓存,保证按 query 区分。
_NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"} _NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"}
_SORT_KEYS = {"mainNetInflow", "changePercent"}
@router.get("", summary="板块列表")
async def sector_list(
type: str = Query("industry", description="板块类型:industry=行业板块, concept=概念板块"),
):
if type not in ("industry", "concept"):
raise HTTPException(status_code=400, detail="板块类型错误,仅支持 industry/concept")
data = await eastmoney.fetch_sector_list(type) def _sort_sectors(data: list[dict], sort: str, order: str) -> list[dict]:
if data: """后端排序:mainNetInflow=资金流入,changePercent=涨幅%"""
return JSONResponse( reverse = order != "asc"
{"data": data, "count": len(data), "type": type}, if sort == "changePercent":
headers=_NO_CACHE_HEADERS, # changePercent 为 None 的排到最后(与方向无关)
return sorted(
data,
key=lambda x: (x.get("changePercent") is None, -(x.get("changePercent") or 0)),
reverse=reverse,
) )
return sorted(data, key=lambda x: -(x.get("mainNetInflow") or 0), reverse=reverse)
async def _sector_response(sector_type: str, sort: str, order: str) -> JSONResponse:
data = await eastmoney.fetch_sector_list(sector_type)
source = None
if not data:
# 降级:通达信 mootdx(不含实时资金流数据) # 降级:通达信 mootdx(不含实时资金流数据)
md_data = await mootdx.fetch_sector_list(type) md_data = await mootdx.fetch_sector_list(sector_type)
if md_data: if md_data:
return JSONResponse( data = md_data
{"data": md_data, "count": len(md_data), "type": type, "source": "mootdx"}, source = "mootdx"
headers=_NO_CACHE_HEADERS,
)
return JSONResponse( if data:
{"data": [], "count": 0, "type": type}, data = _sort_sectors(data, sort, order)
headers=_NO_CACHE_HEADERS,
) payload: dict = {"data": data, "count": len(data), "type": sector_type}
if source:
payload["source"] = source
return JSONResponse(payload, headers=_NO_CACHE_HEADERS)
@router.get("/industry", summary="行业板块列表")
async def sector_industry(
sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"),
order: str = Query("desc", description="排序方向:asc=升序, desc=降序"),
):
if sort not in _SORT_KEYS:
sort = "mainNetInflow"
if order not in ("asc", "desc"):
order = "desc"
return await _sector_response("industry", sort, order)
@router.get("/concept", summary="概念板块列表")
async def sector_concept(
sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"),
order: str = Query("desc", description="排序方向:asc=升序, desc=降序"),
):
if sort not in _SORT_KEYS:
sort = "mainNetInflow"
if order not in ("asc", "desc"):
order = "desc"
return await _sector_response("concept", sort, order)
+12 -4
View File
@@ -460,15 +460,23 @@ export interface SectorResponse {
} }
/** /**
* 获取东方财富板块列表(按主力净流入排序) * 获取东方财富板块列表
* 行业/概念走不同 path/industry、/concept),避免上游反代按 path 缓存忽略 query 导致数据串味
* @param type industry=行业板块, concept=概念板块 * @param type industry=行业板块, concept=概念板块
* @param sort mainNetInflow=资金流入, changePercent=涨幅%
* @param order asc=升序, desc=降序
*/ */
export async function fetchSectors(type: SectorType, signal?: AbortSignal): Promise<SectorItem[]> { export async function fetchSectors(
type: SectorType,
opts?: { sort?: "mainNetInflow" | "changePercent"; order?: "asc" | "desc"; signal?: AbortSignal },
): Promise<SectorItem[]> {
const baseUrl = getApiBaseUrl(); const baseUrl = getApiBaseUrl();
const url = `${baseUrl}/api/sectors?type=${type}`; const sort = opts?.sort ?? "mainNetInflow";
const order = opts?.order ?? "desc";
const url = `${baseUrl}/api/sectors/${type}?sort=${sort}&order=${order}`;
try { try {
const resp = await fetch(url, { method: "GET", signal, cache: "no-store" }); const resp = await fetch(url, { method: "GET", signal: opts?.signal, cache: "no-store" });
if (!resp.ok) return []; if (!resp.ok) return [];
const result: SectorResponse = await resp.json(); const result: SectorResponse = await resp.json();
return result.data || []; return result.data || [];
+40 -29
View File
@@ -1,6 +1,5 @@
import { createFileRoute, Link } from "@tanstack/react-router"; import { createFileRoute, Link } from "@tanstack/react-router";
import { useMemo, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api"; import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { ArrowLeft, RefreshCw, ArrowDown, ArrowUp, TrendingUp, TrendingDown } from "lucide-react"; import { ArrowLeft, RefreshCw, ArrowDown, ArrowUp, TrendingUp, TrendingDown } from "lucide-react";
@@ -9,7 +8,7 @@ export const Route = createFileRoute("/sectors")({
component: SectorsPage, component: SectorsPage,
}); });
/* ── Tabs:行业 / 概念 ── */ /* ── Tabs:行业 / 概念(各自独立 path,互不串数据)── */
const TABS: { key: SectorType; label: string }[] = [ const TABS: { key: SectorType; label: string }[] = [
{ key: "industry", label: "行业" }, { key: "industry", label: "行业" },
{ key: "concept", label: "概念" }, { key: "concept", label: "概念" },
@@ -22,30 +21,27 @@ function SectorsPage() {
const [tab, setTab] = useState<SectorType>("industry"); const [tab, setTab] = useState<SectorType>("industry");
const [sortKey, setSortKey] = useState<SortKey>("mainNetInflow"); const [sortKey, setSortKey] = useState<SortKey>("mainNetInflow");
const [asc, setAsc] = useState(true); const [asc, setAsc] = useState(true);
const [data, setData] = useState<SectorItem[]>([]);
const [loading, setLoading] = useState(true);
const abortRef = useRef<AbortController | null>(null);
// 行业 / 概念 各自独立的 Query,数据完全隔离,杜绝来回切换时的合并 // 每次 tab / 排序变化都重新发起请求(带 no-store,不缓存)
const industryQ = useQuery({ useEffect(() => {
queryKey: ["sectors", "industry"], abortRef.current?.abort();
queryFn: ({ signal }) => fetchSectors("industry", signal), const controller = new AbortController();
staleTime: 30_000, abortRef.current = controller;
retry: false, setLoading(true);
}); fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal })
const conceptQ = useQuery({ .then((items) => {
queryKey: ["sectors", "concept"], if (!controller.signal.aborted) {
queryFn: ({ signal }) => fetchSectors("concept", signal), setData(items);
staleTime: 30_000, setLoading(false);
retry: false, }
}); });
return () => controller.abort();
}, [tab, sortKey, asc]);
const { data = [], isLoading, isFetching, refetch } = // 后端已按 sort/order 排序;此处再排一次作为兜底,确保 UI 一定响应排序
tab === "industry" ? industryQ : conceptQ;
// 切换 tab 时强制重新请求,绕过 React Query 缓存和上游反代缓存,确保拿到对应类型的数据
const handleTab = (t: SectorType) => {
setTab(t);
(t === "industry" ? industryQ : conceptQ).refetch();
};
const sorted = useMemo(() => { const sorted = useMemo(() => {
const dir = asc ? 1 : -1; const dir = asc ? 1 : -1;
return [...data].sort((a, b) => { return [...data].sort((a, b) => {
@@ -63,6 +59,21 @@ function SectorsPage() {
} }
}; };
const reload = () => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal }).then(
(items) => {
if (!controller.signal.aborted) {
setData(items);
setLoading(false);
}
},
);
};
return ( return (
<div className="min-h-screen bg-background"> <div className="min-h-screen bg-background">
{/* 顶栏 */} {/* 顶栏 */}
@@ -75,21 +86,21 @@ function SectorsPage() {
<h1 className="text-base font-semibold"></h1> <h1 className="text-base font-semibold"></h1>
</div> </div>
<button <button
onClick={() => refetch()} onClick={reload}
className="text-muted-foreground hover:text-foreground transition-colors" className="text-muted-foreground hover:text-foreground transition-colors"
> >
<RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} /> <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
</button> </button>
</div> </div>
</header> </header>
{/* Tab 切换:行业 / 概念 */} {/* Tab 切换:行业 / 概念(不同 path 请求) */}
<div className="max-w-5xl mx-auto px-4 mt-4"> <div className="max-w-5xl mx-auto px-4 mt-4">
<div className="flex gap-1 bg-muted rounded-lg p-1"> <div className="flex gap-1 bg-muted rounded-lg p-1">
{TABS.map((t) => ( {TABS.map((t) => (
<button <button
key={t.key} key={t.key}
onClick={() => handleTab(t.key)} onClick={() => setTab(t.key)}
className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-colors ${ className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-colors ${
tab === t.key tab === t.key
? "bg-background text-foreground shadow-sm" ? "bg-background text-foreground shadow-sm"
@@ -115,7 +126,7 @@ function SectorsPage() {
{/* 卡片列表 */} {/* 卡片列表 */}
<div className="max-w-5xl mx-auto px-4 mt-3 pb-8"> <div className="max-w-5xl mx-auto px-4 mt-3 pb-8">
{isLoading ? ( {loading ? (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3"> <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
{Array.from({ length: 20 }).map((_, i) => ( {Array.from({ length: 20 }).map((_, i) => (
<div key={i} className="animate-pulse rounded-xl bg-muted h-32" /> <div key={i} className="animate-pulse rounded-xl bg-muted h-32" />