You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并24小时API令牌存储逻辑的重复代码分支?

Clean Up Duplicate Logic for 24-Hour Token Management

Nice catch on the duplicate code—this kind of repetition makes maintenance harder down the line, so let's fix it by extracting the common logic into a reusable helper method. Here's a streamlined approach that merges the "file missing" and "token expired" scenarios neatly:

Step 1: Extract the Refresh/Save Logic

First, let's pull out the code that fetches a new token and saves it to the file into a private helper method. This way, we only write this logic once:

import os
import json
import datetime as dt
from datetime import timedelta

# Inside your class...
def _refresh_and_save_token(self):
    # Fetch new token via login
    token = self.login()
    # Prepare data with current timestamp
    current_time = dt.now()
    data = {'token': token, 'timestamp': dt.timestamp(current_time)}
    # Ensure the temp directory exists to avoid write errors
    os.makedirs('temp', exist_ok=True)
    # Save token and timestamp to file
    with open("temp/24h_session.json", "w") as f:
        json.dump(data, f)
    return token

Step 2: Simplify the Token Retrieval Logic

Now, the main method can handle all three scenarios with a single check for whether we need to refresh the token:

def get_valid_token(self):
    token_file = 'temp/24h_session.json'
    need_refresh = True
    token = None

    # Check if file exists and token is still valid
    if os.path.isfile(token_file):
        with open(token_file, 'r') as f:
            data = json.load(f)
        
        # Calculate exact expiration timestamp (creation time + 24 hours)
        expiration_timestamp = data['timestamp'] + timedelta(hours=24).total_seconds()
        current_timestamp = dt.timestamp(dt.now())
        
        # Use existing token if it's not expired
        if expiration_timestamp > current_timestamp:
            need_refresh = False
            token = data['token']

    # Refresh token if needed (either file is missing OR token is expired)
    if need_refresh:
        token = self._refresh_and_save_token()

    return token

What This Improves:

  • No duplicate code: The token fetch/save logic lives in one place—if you ever need to change the file path, expiration window, or storage format, you only update it once.
  • Clearer flow: The need_refresh flag makes it obvious when we need a new token, regardless of whether the root cause was a missing file or an expired token.
  • Robustness: Added os.makedirs('temp', exist_ok=True) to avoid errors if the temp directory wasn't created beforehand (your original code might fail here otherwise).
  • Intuitive expiration check: Instead of subtracting 24 hours from the current time, we calculate the exact expiration time by adding 24 hours to the token's creation timestamp—this is easier to read and less prone to off-by-one mistakes.

How to Use It:

Instead of handling the token logic inline, just call self.get_valid_token() whenever you need a valid token—it will automatically handle all three scenarios for you.

内容的提问来源于stack exchange,提问作者Lleims

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:43:10