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

请求开发Python代码,通过OpenAPI查询月度用量及硬限制

Python实现OpenAPI月度用量查询(从本地TXT读取认证信息)

步骤1:准备认证信息文件

创建一个auth.txt文件,按键=值格式存储账号、密码和密钥,每行一个条目:

account=your_account
password=your_password
api_key=your_api_secret_key

步骤2:编写Python代码

下面是完整的实现代码,包含读取认证信息、调用API、解析结果的逻辑:

import requests
from configparser import ConfigParser

def load_auth_info(file_path):
    """从TXT文件加载账号、密码和API密钥"""
    config = ConfigParser()
    # 兼容无section的键值对格式
    config.read_string(f"[auth]\n{open(file_path).read()}")
    return {
        "account": config.get("auth", "account"),
        "password": config.get("auth", "password"),
        "api_key": config.get("auth", "api_key")
    }

def get_monthly_usage(auth_info):
    """调用OpenAPI查询月度用量数据"""
    # 替换为实际的API端点URL
    api_url = "https://api.example.com/v1/usage/monthly"
    
    # 根据API要求构造请求头/参数,这里假设使用API密钥+账号密码的混合认证
    headers = {
        "Authorization": f"Bearer {auth_info['api_key']}",
        "Content-Type": "application/json"
    }
    auth = (auth_info["account"], auth_info["password"])
    
    try:
        response = requests.get(api_url, headers=headers, auth=auth)
        response.raise_for_status()  # 触发HTTP错误抛出
        data = response.json()
        
        # 替换为API响应中实际对应的字段名
        monthly_total = data.get("monthly_usage", {}).get("total", "N/A")
        hard_limit = data.get("limits", {}).get("hard_limit", "N/A")
        
        return {
            "本月累计总用量": monthly_total,
            "硬限制值": hard_limit
        }
    except requests.exceptions.RequestException as e:
        return {"错误": f"API调用失败: {str(e)}"}

if __name__ == "__main__":
    auth = load_auth_info("auth.txt")
    usage_data = get_monthly_usage(auth)
    
    print("月度用量查询结果:")
    for key, value in usage_data.items():
        print(f"- {key}: {value}")

关键说明

  • 认证适配:不同OpenAPI的认证规则不同(比如仅API密钥、仅账号密码或混合模式),请根据目标API文档调整headers和auth参数。
  • 字段替换:代码中monthly_usage.total和limits.hard_limit是示例字段,需要替换为API响应里实际对应的字段路径。
  • 错误处理:代码包含基础HTTP错误捕获,可按需扩展超时、JSON解析失败等异常处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:21:02