处理不同的API响应dtype

发布于 2025-01-22 02:58:42 字数 795 浏览 3 评论 0原文

给定一个基本的API调用 -

response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)
return(response.json())

如果DTYPE变化,您将如何处理响应?例如,有时json,有时.xlsx [二进制]?

上下文:我想创建一个测试3X标准的函数:

  1. 响应是包含 persect> persion_complete - 值用于添加到进度栏中。此apir_response告诉我所请求的数据尚未准备就绪,并采用percen_complete值以更新进度栏。
  2. 响应是包含 meta的JSON对象 - 如果为true,则请求的数据已作为JSON对象返回,api_response应返回,准备就绪用于另一个功能。
  3. 响应是.xlsx file(binary ??) - 如果为true,则请求的数据已在.xlsx格式中返回,并且<代码>应返回api_response ,准备在另一个功能中使用。

欢迎任何建议吗?

Given a basic API call -

response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)
return(response.json())

How would you handle the response if the Dtype varied? E.g., sometimes json, sometimes .xlsx [binary]?

Context: I want to create a function that tests 3x criteria:

  1. Response is JSON object containing percent_complete - if TRUE, then the percent_complete value is used to add to a progress bar. This apir_response tells me the requested data isn't ready yet and takes percent_complete value to update a progress bar.
  2. Response is JSON object containing meta - if TRUE, then the requested data has been returned as a JSON object, and api_response should be returned, ready to be used in another function.
  3. Response is an .xlsx file (binary??) - if TRUE, then the requested data has been returned in .xlsx format, and api_response should be returned, ready for use in another function.

Any suggestions would be welcome?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

菩提树下叶撕阳。 2025-01-29 02:58:42

您可以使用尝试除外

response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)

try:
    data = response.json()
    # No exceptions here means that we get and parse valid json
    if 'percent_complete' in data:
        """Handle option 1 here."""

    elif 'meta' in data:
        """Handle option 2 here."""

    else:
        # Unknown format, so return None
        return None
except:
    # Data is non json, as exception occured
    """Try handling option 3 here by accessing `response.content`."""

You could use try and except for that:

response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)

try:
    data = response.json()
    # No exceptions here means that we get and parse valid json
    if 'percent_complete' in data:
        """Handle option 1 here."""

    elif 'meta' in data:
        """Handle option 2 here."""

    else:
        # Unknown format, so return None
        return None
except:
    # Data is non json, as exception occured
    """Try handling option 3 here by accessing `response.content`."""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文