优化
This commit is contained in:
+32
-33
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from api.types.colg import HistoryGold, OfficialGold, RealTimeGold
|
||||
from api.core.Gzip import register_gzip_request
|
||||
@@ -6,7 +7,7 @@ import json
|
||||
from fastapi import APIRouter, Query
|
||||
from api.core.Response import response
|
||||
from api.core.Redis import get_redis_info, get_redis_info_async
|
||||
from api.dp import RedisDep
|
||||
from api.dp import AsyncRedisDep, RedisDep
|
||||
from typing import Annotated
|
||||
import requests
|
||||
from config.main import config
|
||||
@@ -15,6 +16,7 @@ from api.core.Response import Return as Response
|
||||
import aiohttp
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger('dcalc.colg')
|
||||
|
||||
register_gzip_request(router)
|
||||
|
||||
@@ -39,6 +41,29 @@ payload_helper = {
|
||||
'token': config.HELPER_TOKEN,
|
||||
}
|
||||
|
||||
OFFICIAL_GOLD_URL = 'https://dzhu.qq.com/zangyi/activity/app'
|
||||
OFFICIAL_GOLD_REGIONS = ('1', '2', '3A', '3B', '4', '5', '6', '7')
|
||||
|
||||
|
||||
async def _fetch_official_gold() -> list[dict]:
|
||||
timeout = aiohttp.ClientTimeout(total=10)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
|
||||
async def fetch_region(region: str) -> dict:
|
||||
form = {**payload_helper, 'serverNo': region}
|
||||
async with session.post(OFFICIAL_GOLD_URL, data=form) as resp:
|
||||
resp.raise_for_status()
|
||||
payload = await resp.json(content_type=None)
|
||||
data = payload['data']
|
||||
return {
|
||||
'updataTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'region': f'跨{region}',
|
||||
'goldDealRank': [int(item['price']) for item in data['godDealRank']],
|
||||
'goldTopDealRank': [int(item['price']) for item in data['godTopDealRank']],
|
||||
}
|
||||
|
||||
return await asyncio.gather(*(fetch_region(region) for region in OFFICIAL_GOLD_REGIONS))
|
||||
|
||||
|
||||
def get_date_str(timestamp: int) -> str:
|
||||
utc_time = datetime.fromtimestamp(timestamp, tz=timezone.utc)
|
||||
@@ -47,7 +72,7 @@ def get_date_str(timestamp: int) -> str:
|
||||
|
||||
|
||||
@router.get('/gold/realtime/', operation_id='realtimeGold', response_model=Response[list[RealTimeGold]])
|
||||
async def get_real_time_gold(redis: RedisDep) -> Response[list[RealTimeGold]]:
|
||||
def get_real_time_gold(redis: RedisDep) -> Response[list[RealTimeGold]]:
|
||||
"""
|
||||
返回所有跨区的实时金价信息
|
||||
"""
|
||||
@@ -74,7 +99,7 @@ async def get_real_time_gold(redis: RedisDep) -> Response[list[RealTimeGold]]:
|
||||
|
||||
|
||||
@router.get('/gold/history/', operation_id='historyGold', response_model=Response[HistoryGold] | Response[None])
|
||||
async def get_history_gold(region: Annotated[int, Query(..., description='跨区id')], timeRange: Annotated[int, Query(..., description='时间跨度天数')] = 7) -> Response[HistoryGold] | Response[None]:
|
||||
def get_history_gold(region: Annotated[int, Query(..., description='跨区id')], timeRange: Annotated[int, Query(..., description='时间跨度天数')] = 7) -> Response[HistoryGold] | Response[None]:
|
||||
"""
|
||||
获取历史金价数据
|
||||
|
||||
@@ -146,7 +171,7 @@ async def get_history_gold(region: Annotated[int, Query(..., description='跨区
|
||||
|
||||
|
||||
@router.get('/gold/official/', operation_id='officialGold', response_model=Response[list[OfficialGold]])
|
||||
async def get_official_gold(redis: RedisDep) -> Response[list[OfficialGold]]:
|
||||
async def get_official_gold(redis: AsyncRedisDep) -> Response[list[OfficialGold]]:
|
||||
"""
|
||||
获取DNF官方金币寄售实时数据
|
||||
|
||||
@@ -156,36 +181,10 @@ async def get_official_gold(redis: RedisDep) -> Response[list[OfficialGold]]:
|
||||
- 该接口会返回所有跨区的官方金币寄售数据,包括最低成交价排名前5的价格和最高成交价排名前5的价格
|
||||
- 数据来源于DNF官方提供的接口,可能会有一定的延迟和不稳定性
|
||||
"""
|
||||
official_url = 'https://dzhu.qq.com/zangyi/activity/app'
|
||||
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
||||
key = 'openapi:colg:real_time_gold_officical'
|
||||
list = ['1', '2', '3A', '3B', '4', '5', '6', '7']
|
||||
try:
|
||||
|
||||
async def get_data():
|
||||
datas = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
tasks = []
|
||||
for i in list:
|
||||
payload_helper['serverNo'] = i
|
||||
query = '&'.join(f'{k}={v}' for k, v in payload_helper.items())
|
||||
tasks.append(session.post(official_url, data=query, headers=headers, timeout=10))
|
||||
responses = await asyncio.gather(*tasks)
|
||||
for index, resp in enumerate(responses):
|
||||
res = json.loads(await resp.read())
|
||||
datas.append(
|
||||
{
|
||||
'updataTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'region': f'跨{list[index]}',
|
||||
'goldDealRank': [int(i.get('price')) for i in res['data']['godDealRank']],
|
||||
'goldTopDealRank': [int(i.get('price')) for i in res['data']['godTopDealRank']],
|
||||
}
|
||||
)
|
||||
return datas
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
data = await get_redis_info_async(redis, key, _fetch_official_gold, 30 * 60)
|
||||
except Exception:
|
||||
logger.exception('fetch official gold failed')
|
||||
return response(data=[])
|
||||
# 设置半小时过期一次
|
||||
data = await get_redis_info_async(redis, key, get_data, 30 * 60)
|
||||
return response(data=data)
|
||||
|
||||
Reference in New Issue
Block a user