Skip to content

Commit c7db971

Browse files
committed
refactor(bot): 移除汇率数据缓存状态和下次更新时间信息
- 从 fetch_and_parse_rate_data 和 get_exchange_rate 函数中移除了缓存状态和下次更新时间的返回值 - 更新了相关命令的响应消息,不再包含缓存状态和下次更新时间信息 - 简化了数据获取逻辑,提高了代码可读性和性能
1 parent b5744e5 commit c7db971

File tree

2 files changed

+26
-59
lines changed

2 files changed

+26
-59
lines changed

app/bot/handlers.py

Lines changed: 11 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ async def rate_command(message: types.Message, bot=None):
6868
# Get the URL from environment variable
6969
url = settings.BOC_URL
7070

71-
# Fetch exchange rate data directly with cache info
72-
data, is_cached, next_update = await fetch_and_parse_rate_data(url)
71+
# Fetch exchange rate data directly
72+
data = await fetch_and_parse_rate_data(url)
7373

7474
if not data or "currencies" not in data or not data["currencies"]:
7575
await bot_to_use.send_message(
@@ -81,15 +81,9 @@ async def rate_command(message: types.Message, bot=None):
8181
# Get the last updated time
8282
last_updated = data.get("last_updated", "未知")
8383

84-
# Add cache status and next update time
85-
cache_status = "✅ 数据来源: 缓存" if is_cached else "🔄 数据来源: 实时获取"
86-
next_update_str = next_update.strftime("%Y-%m-%d %H:%M:%S")
87-
8884
# Start response with update time header including the timestamp
8985
response_lines = [
90-
f"汇率更新时间\n{last_updated}\n",
91-
f"{cache_status}",
92-
f"下次更新时间: {next_update_str}\n"
86+
f"汇率更新时间\n{last_updated}\n"
9387
]
9488

9589
# Get supported currencies and their Chinese names
@@ -160,31 +154,24 @@ async def convert_command(message: types.Message, bot=None):
160154
)
161155
return
162156

163-
rate_info = await get_exchange_rate(from_currency, to_currency)
164-
rate, is_cached, next_update = rate_info
157+
rate = await get_exchange_rate(from_currency, to_currency)
165158

166159
if rate:
167160
# Get the last updated time
168161
from app.services.exchange_rate import fetch_and_parse_rate_data
169162
from app.core.config import settings
170163

171164
# Fetch data to get the update time
172-
data, _, _ = await fetch_and_parse_rate_data(settings.BOC_URL)
165+
data = await fetch_and_parse_rate_data(settings.BOC_URL)
173166
last_updated = data.get("last_updated", "未知")
174167

175-
# Add cache status and next update time
176-
cache_status = "✅ 数据来源: 缓存" if is_cached else "🔄 数据来源: 实时获取"
177-
next_update_str = next_update.strftime("%Y-%m-%d %H:%M:%S")
178-
179168
converted_amount = amount * rate
180169
await bot_to_use.send_message(
181170
chat_id=message.chat.id,
182171
text=f"💱 货币转换结果:\n"
183172
f"{amount:.2f} {from_currency} = {converted_amount:.2f} {to_currency}\n"
184173
f"(汇率: 1 {from_currency} = {rate:.4f} {to_currency})\n\n"
185-
f"汇率更新时间\n{last_updated}\n"
186-
f"{cache_status}\n"
187-
f"下次更新时间: {next_update_str}"
174+
f"汇率更新时间\n{last_updated}"
188175
)
189176
else:
190177
await bot_to_use.send_message(
@@ -230,20 +217,14 @@ async def currency_command(message: types.Message, bot=None):
230217
from app.core.config import settings
231218

232219
# Fetch data to get the update time
233-
data, is_cached, next_update = await fetch_and_parse_rate_data(settings.BOC_URL)
220+
data = await fetch_and_parse_rate_data(settings.BOC_URL)
234221
last_updated = data.get("last_updated", "未知")
235222

236-
# Add cache status and next update time
237-
cache_status = "✅ 数据来源: 缓存" if is_cached else "🔄 数据来源: 实时获取"
238-
next_update_str = next_update.strftime("%Y-%m-%d %H:%M:%S")
239-
240223
await bot_to_use.send_message(
241224
chat_id=message.chat.id,
242225
text=f"💰 支持的货币列表:\n{currency_list}\n\n"
243226
f"使用 /rate 或 /convert 或 /cny_convert 获取汇率和转换货币。\n\n"
244-
f"汇率更新时间\n{last_updated}\n"
245-
f"{cache_status}\n"
246-
f"下次更新时间: {next_update_str}"
227+
f"汇率更新时间\n{last_updated}"
247228
)
248229

249230
async def cny_convert_command(message: types.Message, bot=None):
@@ -267,31 +248,24 @@ async def cny_convert_command(message: types.Message, bot=None):
267248
amount = float(args[2])
268249
to_currency = "CNY"
269250

270-
rate_info = await get_exchange_rate(from_currency, to_currency)
271-
rate, is_cached, next_update = rate_info
251+
rate = await get_exchange_rate(from_currency, to_currency)
272252

273253
if rate:
274254
# Get the last updated time
275255
from app.services.exchange_rate import fetch_and_parse_rate_data
276256
from app.core.config import settings
277257

278258
# Fetch data to get the update time
279-
data, _, _ = await fetch_and_parse_rate_data(settings.BOC_URL)
259+
data = await fetch_and_parse_rate_data(settings.BOC_URL)
280260
last_updated = data.get("last_updated", "未知")
281261

282-
# Add cache status and next update time
283-
cache_status = "✅ 数据来源: 缓存" if is_cached else "🔄 数据来源: 实时获取"
284-
next_update_str = next_update.strftime("%Y-%m-%d %H:%M:%S")
285-
286262
converted_amount = amount * rate
287263
await bot_to_use.send_message(
288264
chat_id=message.chat.id,
289265
text=f"💱 转换为人民币结果:\n"
290266
f"{amount:.2f} {from_currency} = {converted_amount:.2f} {to_currency}\n"
291267
f"(汇率: 1 {from_currency} = {rate:.4f} {to_currency})\n\n"
292-
f"汇率更新时间\n{last_updated}\n"
293-
f"{cache_status}\n"
294-
f"下次更新时间: {next_update_str}"
268+
f"汇率更新时间\n{last_updated}"
295269
)
296270
else:
297271
await bot_to_use.send_message(

app/services/exchange_rate.py

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,21 @@
2020
# Default to 60 minutes (3600 seconds) if not specified
2121
CACHE_TTL = int(getattr(settings, "CACHE_TTL_MINUTES", 10)) * 60
2222

23-
CACHE_TTL = int(getattr(settings, "CACHE_TTL_MINUTES", 10)) * 60
24-
2523
# Create a global cache to store timestamps
2624
_cache_timestamps = {}
2725
@cached(ttl=CACHE_TTL, cache=SimpleMemoryCache)
2826
# Custom caching implementation to track cache status
29-
async def fetch_and_parse_rate_data(url: str, timeout: int = 10) -> Tuple[Dict[str, Any], bool, datetime]:
27+
async def fetch_and_parse_rate_data(url: str, timeout: int = 10) -> Dict[str, Any]:
3028
"""
3129
Asynchronously fetches exchange rate data from the specified URL and parses it,
32-
with caching and cache status tracking.
30+
with caching.
3331
3432
Args:
3533
url: The URL to fetch the exchange rate data from
3634
timeout: Request timeout in seconds
3735
3836
Returns:
39-
Tuple containing:
40-
- Dictionary containing the parsed exchange rate data
41-
- Boolean indicating whether the result is from cache
42-
- Datetime object indicating when the cache will be updated next
37+
Dictionary containing the parsed exchange rate data.
4338
4439
Raises:
4540
Exception: If there's an error during fetching or parsing the data
@@ -67,9 +62,8 @@ async def fetch_and_parse_rate_data(url: str, timeout: int = 10) -> Tuple[Dict[s
6762

6863
logger.info(f"Successfully fetched and parsed exchange rate data: {exchange_data}")
6964

70-
71-
72-
return exchange_data, None, None
65+
# Return only the data
66+
return exchange_data
7367

7468
except httpx.TimeoutException:
7569
logger.error(f"Timeout error while fetching data from {url}")
@@ -198,7 +192,7 @@ def _parse_exchange_rate_data(soup: BeautifulSoup) -> Dict[str, Any]:
198192
logger.error(f"Error parsing exchange rate data: {e}")
199193
return {}
200194

201-
async def get_exchange_rate(from_currency: str, to_currency: str) -> Union[Tuple[Optional[float], bool, datetime], Optional[float]]:
195+
async def get_exchange_rate(from_currency: str, to_currency: str) -> Optional[float]:
202196
"""
203197
Get the exchange rate between two currencies based on Cash Selling Rate.
204198
@@ -207,18 +201,16 @@ async def get_exchange_rate(from_currency: str, to_currency: str) -> Union[Tuple
207201
to_currency: The target currency code (e.g., "EUR")
208202
209203
Returns:
210-
A tuple containing:
211-
- The exchange rate as a float, or None if the rate couldn't be retrieved
212-
- Boolean indicating whether the result is from cache
213-
- Datetime object indicating when the cache will be updated next
204+
The exchange rate as a float, or None if the rate couldn't be retrieved.
214205
"""
215206
try:
216207
# Get the URL from environment variable
217208
from app.core.config import Settings
218209
settings = Settings()
219210
url = settings.BOC_URL
220211

221-
data, is_cached, next_update = await fetch_and_parse_rate_data(url)
212+
# Fetch data (cache status and next update are no longer returned)
213+
data = await fetch_and_parse_rate_data(url)
222214

223215
# This logic will depend on the structure of your parsed data
224216
if "currencies" not in data or not data["currencies"]:
@@ -254,7 +246,7 @@ async def get_exchange_rate(from_currency: str, to_currency: str) -> Union[Tuple
254246

255247
# For CNY conversion, return the rate divided by 100
256248
# This is because rates are quoted as CNY per 100 foreign currency units
257-
return from_rate / 100, is_cached, next_update
249+
return from_rate / 100
258250

259251
# If from_currency is CNY, we need to handle differently
260252
elif from_currency == "CNY":
@@ -268,7 +260,7 @@ async def get_exchange_rate(from_currency: str, to_currency: str) -> Union[Tuple
268260
return None
269261

270262
# For converting from CNY, we need reciprocal of the rate divided by 100
271-
return 100 / to_rate, is_cached, next_update
263+
return 100 / to_rate
272264

273265
# Normal case - converting between two non-CNY currencies
274266
else:
@@ -292,13 +284,14 @@ async def get_exchange_rate(from_currency: str, to_currency: str) -> Union[Tuple
292284

293285
# Calculate exchange rate between the two currencies
294286
exchange_rate = to_rate / from_rate
295-
return exchange_rate, is_cached, next_update
287+
return exchange_rate
296288

297289
# Note: This code is unreachable due to the return statements above
298290
logger.error(f"Exchange rate not available for {from_currency} to {to_currency}")
299-
return None, is_cached, next_update
291+
return None
300292

301293
except Exception as e:
302294
logger.error(f"Error getting exchange rate: {e}")
303295
logger.exception("Stack trace:")
304-
return None, False, datetime.now() + timedelta(seconds=CACHE_TTL)
296+
# Return None on error, as cache status/next update are no longer relevant here
297+
return None

0 commit comments

Comments
 (0)