编写巨大的Python api 包装器

问题描述 投票:0回答:1

我要为一些 api 编写库,其中有 150 多个具有相同语法的方法,我的代码如下所示:

class MyApiClient()
   def __init__(self):
        ... some logic ...
   def get_attribute1(self, attbibute_id):
       r = requests.get(f"self.base_url/{method_url}")
       *some response parse logic*

它将是具有 150 多个方法的类,我可以为每个范围执行单个类,但它仍然是巨大的回复代码 - 4-5 个类,具有 30-40 个方法。

问题:是否有任何 python 库可以简化这项工作?例如 - 简单的装饰器或其他东西:

@simple_http(method='GET', path="/method_url", raw_response=True)
def get_attribute1(self, attbibute_id):
    ...  # exactly what writed - just no code inside, all logic inside decorator,
# which takes func args and do request and return raw or parse someway

我相信一些具有该逻辑的库已经存在,但找不到任何 deacator 可以像

def simple_http(method='GET', path='/', raw_response=False):
    def decorator(func):
        def wrapper(*args, **kwargs):
            url = "http://api.example.com" + path  # Base URL
            headers = {'Content-Type': 'application/json'}  # Example headers

            if method.upper() == 'GET':
                response = requests.get(url, headers=headers, params=kwargs)
            elif method.upper() == 'POST':
                response = requests.post(url, headers=headers, json=kwargs)
            # Add more cases for other HTTP methods as needed

            if raw_response:
                return response
            else:
                return response.json()

        return wrapper
    return decorator
python api http python-requests
1个回答
0
投票

装饰器在方法中看起来与

return self._request('GET', f'breed/{breed_name}/list')
相同,所以也许我会编写lib来在装饰器上执行此操作并考虑异步装饰器

© www.soinside.com 2019 - 2024. All rights reserved.