|
16 | 16 |
|
17 | 17 | trendingRoute = APIRouter(prefix='/api/trending', tags=['Trending']) |
18 | 18 |
|
| 19 | +ALLOWED_PERIODS = {'day', 'week', 'month', 'all'} |
| 20 | +ALLOWED_TYPE_IDS = {1, 2, 3, 4} |
| 21 | + |
19 | 22 |
|
20 | 23 | async def gen_url(typeID: int, period: str, amount=10): |
21 | | - """ |
22 | | - 传入的值必须经过检查,否则可能会导致 API 请求失败。 |
23 | | - """ |
24 | | - if period not in ['day', 'week', 'month', 'all']: |
25 | | - return JSONResponse(status_code=400, |
26 | | - content={'error': 'Invalid period parameter, must be one of: day, week, month, all'}) |
27 | | - if typeID not in [1, 2, 3, 4]: |
28 | | - return JSONResponse(status_code=400, content={ |
29 | | - 'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 24 | + if period not in ALLOWED_PERIODS: |
| 25 | + return JSONResponse(status_code=400, content={'error': 'Invalid period parameter, must be one of: day, week, month, all'}) |
| 26 | + if typeID not in ALLOWED_TYPE_IDS: |
| 27 | + return JSONResponse(status_code=400, content={'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
30 | 28 | vv = await gen_vv() |
31 | | - url = f"https://api.olelive.com/v1/pub/index/vod/data/rank/{period}/{typeID}/{amount}?_vv={vv}" |
32 | | - return url |
| 29 | + return f"https://api.olelive.com/v1/pub/index/vod/data/rank/{period}/{typeID}/{amount}?_vv={vv}" |
33 | 30 |
|
34 | 31 |
|
35 | 32 | async def gen_url_v2(typeID: int, amount=10): |
36 | | - """ |
37 | | - 传入的值必须经过检查,否则可能会导致 API 请求失败。 |
38 | | - """ |
39 | | - if typeID not in [1, 2, 3, 4]: |
40 | | - return JSONResponse(status_code=400, content={ |
41 | | - 'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 33 | + if typeID not in ALLOWED_TYPE_IDS: |
| 34 | + return JSONResponse(status_code=400, content={'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
42 | 35 | vv = await gen_vv() |
43 | | - url = f"https://api.olelive.com/v1/pub/index/vod/hot/{typeID}/0/{amount}?_vv={vv}" |
44 | | - return url |
| 36 | + return f"https://api.olelive.com/v1/pub/index/vod/hot/{typeID}/0/{amount}?_vv={vv}" |
45 | 37 |
|
46 | 38 |
|
47 | 39 | @trendingRoute.post('/{period}/trend') |
48 | 40 | async def fetch_trending_data(request: Request, period: Optional[str] = 'day'): |
49 | | - """ |
50 | | - Fetch trending data from the OLE API. |
51 | | - :param request: The incoming request. |
52 | | - :parameter period: The period of time to fetch trending data for. --> str Options: 'day', 'week', 'month', 'all' |
53 | | - :parameter typeID: The type ID of the item. --> int |
54 | | - typeID docs: |
55 | | - 1: 电影 |
56 | | - 2: 电视剧(连续剧) |
57 | | - 3: 综艺 |
58 | | - 4: 动漫 |
59 | | - :parameter amount: The number of items to fetch. --> int default: 10 |
60 | | - """ |
61 | 41 | try: |
62 | | - data = await request.json() |
| 42 | + body = await request.json() |
63 | 43 | try: |
64 | | - typeID = data['params']['typeID'] |
| 44 | + typeID = body['params']['typeID'] |
65 | 45 | logging.info(f"typeID1: {typeID}") |
66 | | - except KeyError as e: |
67 | | - return JSONResponse(status_code=400, content={'error': f"Where is your param?"}) |
| 46 | + except KeyError: |
| 47 | + return JSONResponse(status_code=400, content={'error': "Where is your param?"}) |
68 | 48 | except JSONDecodeError as e: |
69 | 49 | logging.error(f"JSONDecodeError: {e}, hint: request.json() failed, step fetch_trending_data") |
70 | | - return JSONResponse(status_code=400, content={'error': f"Where is your param?"}) |
| 50 | + return JSONResponse(status_code=400, content={'error': "Where is your param?"}) |
| 51 | + |
71 | 52 | if period is None: |
72 | 53 | logging.error(f"period: {period}, hint: period is None, step fetch_trending_data") |
73 | 54 | return JSONResponse(status_code=400, content={'error': 'Missing required parameters: period'}) |
74 | 55 | if typeID is None: |
75 | 56 | logging.info(f"typeID: {typeID}, hint:typeID is None, step fetch_trending_data") |
76 | 57 | return JSONResponse(status_code=400, content={'error': 'Missing required parameters: typeID'}) |
77 | | - if period not in ['day', 'week', 'month', 'all']: |
| 58 | + if period not in ALLOWED_PERIODS: |
78 | 59 | logging.error(f"period: {period}, hint:period not in ['day', 'week', 'month', 'all]") |
79 | | - return JSONResponse(status_code=400, |
80 | | - content={'error': 'Invalid period parameter, must be one of: day, week, month, all'}) |
81 | | - if typeID not in [1, 2, 3, 4]: |
| 60 | + return JSONResponse(status_code=400, content={'error': 'Invalid period parameter, must be one of: day, week, month, all'}) |
| 61 | + if typeID not in ALLOWED_TYPE_IDS: |
82 | 62 | logging.error(f"typeID: {typeID}, hint:typeID not in [1,2,3,4]") |
83 | | - return JSONResponse(status_code=400, content={ |
84 | | - 'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 63 | + return JSONResponse(status_code=400, content={'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 64 | + |
85 | 65 | url = await gen_url(typeID, period, amount=10) |
86 | 66 | logging.info(f"Fetching trending data from: {url}") |
| 67 | + |
| 68 | + resp = None |
| 69 | + api_payload = None |
87 | 70 | try: |
88 | 71 | async with httpx.AsyncClient() as client: |
89 | | - response = await client.get(url, headers={'User-Agent': _getRandomUserAgent()}, timeout=30) |
90 | | - data = response.json() |
91 | | - return JSONResponse(status_code=200, content=data) |
| 72 | + resp = await client.get(url, headers={'User-Agent': _getRandomUserAgent()}, timeout=30) |
| 73 | + api_payload = resp.json() |
| 74 | + return JSONResponse(status_code=200, content=api_payload) |
92 | 75 | except httpx.RequestError as e: |
93 | | - print(data) |
| 76 | + logging.debug(f"snapshot: {api_payload}") |
94 | 77 | return JSONResponse(status_code=500, content={'error': f"An error occurred: {e}"}) |
95 | 78 | except httpx.HTTPStatusError as e: |
96 | | - print(data) |
| 79 | + logging.debug(f"snapshot: {api_payload}") |
97 | 80 | return JSONResponse(status_code=500, content={'error': f"An HTTP error occurred: {e}"}) |
98 | 81 | except Exception as e: |
99 | | - print(data) |
100 | | - return JSONResponse(status_code=500, content={'error': f"An error occurred: {e}, response: {response.text}"}) |
| 82 | + raw_text = resp.text if resp is not None else "" |
| 83 | + logging.debug(f"snapshot: {api_payload}") |
| 84 | + return JSONResponse(status_code=500, content={'error': f"An error occurred: {e}, response: {raw_text}"}) |
101 | 85 |
|
102 | 86 |
|
103 | 87 | @trendingRoute.api_route('/v2/{typeID}', methods=['POST'], dependencies=[Depends(RateLimiter(times=2, seconds=1))]) |
104 | 88 | async def fetch_trending_data_v2(request: Request, typeID: Optional[int] = None): |
105 | | - """ |
106 | | - Fetch trending data from the OLE API. |
107 | | - :param request: The incoming request. |
108 | | - :parameter typeID: The type ID of the item. --> int |
109 | | - typeID docs: |
110 | | - 1: 电影 |
111 | | - 2: 电视剧(连续剧) |
112 | | - 3: 综艺 |
113 | | - 4: 动漫 |
114 | | - :parameter amount: The number of items to fetch. --> int default: 10 |
115 | | - """ |
116 | 89 | try: |
117 | 90 | amount = request.query_params['amount'] |
118 | | - except KeyError as e: |
| 91 | + except KeyError: |
119 | 92 | amount = 10 |
| 93 | + |
120 | 94 | if typeID is None: |
121 | 95 | logging.info(f"typeID: {typeID}, hint:typeID is None, step fetch_trending_data") |
122 | 96 | return JSONResponse(status_code=400, content={'error': 'Missing required parameters: typeID'}) |
123 | | - if typeID not in [1, 2, 3, 4]: |
| 97 | + if typeID not in ALLOWED_TYPE_IDS: |
124 | 98 | logging.error(f"typeID: {typeID}, hint:typeID not in [1,2,3,4]") |
125 | | - return JSONResponse(status_code=400, content={ |
126 | | - 'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 99 | + return JSONResponse(status_code=400, content={'error': 'Invalid typeID parameter, must be one of: 1 --> 电影, 2 --> 电视剧(连续剧), 3 --> 综艺, 4 --> 动漫'}) |
| 100 | + |
127 | 101 | redis_key = f"trending_v2_cache_{datetime.datetime.now().strftime('%Y-%m-%d')}_{typeID}_{amount}" |
128 | | - if await get_key(redis_key): |
| 102 | + cached = await get_key(redis_key) |
| 103 | + if cached: |
129 | 104 | logging.info(f"Hit cache for key: {redis_key}") |
130 | | - data = await get_key(redis_key) |
131 | | - data = json.loads(data) |
132 | | - return JSONResponse(status_code=200, content=data) |
133 | | - else: |
134 | | - url = await gen_url_v2(typeID, amount) |
135 | | - logging.info(f"Fetching trending data from: {url}") |
136 | | - try: |
137 | | - async with httpx.AsyncClient() as client: |
138 | | - response = await client.get(url, headers={'User-Agent': _getRandomUserAgent()}, timeout=30) |
139 | | - data = json.dumps(response.json()) |
140 | | - await set_key(redis_key, data, 60 * 60 * 24) |
141 | | - return JSONResponse(status_code=200, content=json.loads(data)) |
142 | | - except httpx.RequestError as e: |
143 | | - return JSONResponse(status_code=500, content={'error': f"An error occurred: {e}"}) |
| 105 | + return JSONResponse(status_code=200, content=json.loads(cached)) |
| 106 | + |
| 107 | + url = await gen_url_v2(typeID, amount) |
| 108 | + logging.info(f"Fetching trending data from: {url}") |
| 109 | + try: |
| 110 | + async with httpx.AsyncClient() as client: |
| 111 | + response = await client.get(url, headers={'User-Agent': _getRandomUserAgent()}, timeout=30) |
| 112 | + payload = json.dumps(response.json()) |
| 113 | + await set_key(redis_key, payload, 60 * 60 * 24) |
| 114 | + return JSONResponse(status_code=200, content=json.loads(payload)) |
| 115 | + except httpx.RequestError as e: |
| 116 | + return JSONResponse(status_code=500, content={'error': f"An error occurred: {e}"}) |
0 commit comments