【发布时间】:2019-06-04 12:54:04
【问题描述】:
我使用 requests ratelimit 和 backoff 库创建了一个通用函数。该函数的目标是实现以下逻辑:
如果返回对象的状态不是 200 也不是 404 => 引发错误(这样如果我有连接错误
backoff最多可以尝试一定次数)如果返回对象的状态为404 =>返回错误字典
否则返回 r.json
这是我的功能
import requests
from requests import ConnectionError
from ratelimit import limits, sleep_and_retry
from backoff import on_exception, expo
@sleep_and_retry # if we exceed the ratelimit imposed by @limits forces sleep until we can start again.
@on_exception(expo, ConnectionError, max_tries=10)
@limits(calls=500, period=FIVE_MINUTES)
def call_api(url, api_key):
r = requests.get(url, auth=(api_key, ""))
if not (r.status_code is 200 or r.status_code is 404):
r.raise_for_status()
elif r.status_code is 404:
return dict({"error": "not found"})
else:
return r.json()
实际发生的情况是,如果我有一个 404 r.raise_for_status() 被激活 - 这暗示我的逻辑有问题。
我对这个逻辑做了一个抽象,确实:
def logic_try(value):
if not (value is 200 or value is 404):
print("stopped with value {}".format(value))
elif value is 404:
return dict({"error":value})
else:
return dict({"correct": value})
# calls
logic_try(200)
§ {'correct': 200}
logic_try(404)
§ stopped with value 404 # should return {"error":value}
logic_try(400):
§ stopped with value 400
我希望函数首先检查 r.status i not 200 nor 404 并引发错误状态,以便装饰器可以再次调用。然后检查 r.status 是否为 404,在这种情况下返回我存储在 pg 表中的错误字典,最后,所有其他情况应该简单地返回 r.json(),因为我假设 r.status 是 200。
【问题讨论】:
-
aaaaa 我觉得很傻。谢谢。
标签: python api if-statement request logical-operators