处理错误api的常规功能

时间:2019-06-04 12:54:04

标签: python api if-statement request logical-operators

我使用requests ratelimitbackoff库创建了一个通用函数。此功能的目的是实现以下逻辑:

  • 如果返回的对象的状态不是200也不是404 =>引发错误(因此,如果我遇到连接错误,backoff可以尝试一定次数)

    < / li>
  • 如果返回的对象的状态为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我 not 200 nor 404并提高错误状态,以便装饰器可以再次调用。然后检查r.status是否为404,在这种情况下返回一个错误字典,该字典存储在pg表中,最后,所有其他情况都应简单地返回r.json(),因为我假设r.status为200。

1 个答案:

答案 0 :(得分:0)

区别在于使用is而不是==

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 == 200 or r.status_code == 404):
        r.raise_for_status()

    elif r.status_code == 404:
        return dict({"error": "not found"})

    else:
        return r.json()