为了优化上面的代码,可以考虑以下几点:

  1. 将代码封装成一个函数,方便复用和调用。
  2. 使用异常处理来处理请求中可能发生的错误,例如网络连接错误、API认证错误等。
  3. 使用f-string来格式化字符串,使代码更简洁易读。
  4. 使用requests.exceptions.RequestException来捕获所有请求异常,并输出错误信息。
  5. 使用requests.Session()来管理请求,以便在多次请求中复用连接。

下面是优化后的代码示例:

import datetime
import requests

def get_subscription_usage(apikey):
    try:
        session = requests.Session()
        subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"
        headers = {
            "Authorization": f"Bearer {apikey}",
            "Content-Type": "application/json"
        }
        subscription_response = session.get(subscription_url, headers=headers)
        subscription_response.raise_for_status()
        data = subscription_response.json()
        total = data.get("hard_limit_usd")

        start_date = (datetime.datetime.now() - datetime.timedelta(days=99)).strftime("%Y-%m-%d")
        end_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        billing_url = f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"
        billing_response = session.get(billing_url, headers=headers)
        billing_response.raise_for_status()
        data = billing_response.json()
        total_usage = data.get("total_usage") / 100
        daily_costs = data.get("daily_costs")
        days = min(5, len(daily_costs))
        recent = f"最近{days}天使用情况\n"
        for i in range(days):
            cur = daily_costs[-i-1]
            date = datetime.datetime.fromtimestamp(cur.get("timestamp")).strftime("%Y-%m-%d")
            line_items = cur.get("line_items")
            cost = sum(item.get("cost") for item in line_items)
            recent += f"\t{date}\t{cost / 100}\n"

        return f"\n总额:\t{total:.4f}\n已用:\t{total_usage:.4f}\n剩余:\t{total-total_usage:.4f}\n\n{recent}"
    except requests.exceptions.RequestException as e:
        return str(e)

使用示例:

apikey = "your_api_key"
result = get_subscription_usage(apikey)
print(result)
``
apikey = subscription_url = httpsapiopenaicomv1dashboardbillingsubscription headers = Authorization Bearer + apikey Content-Type applicationjson subscription_response = r

原文地址: https://www.cveoy.top/t/topic/hUM2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录