将高级客户端实现与底层crud分离。
api-client的Python项目详细描述
python客户端抽象
我经常发现我经常给 以提供有关第三方API的抽象。
这个客户机抽象旨在减少编写客户机的开销, 并且应该允许api的使用者将注意力集中在高层 实现,而不是客户端本身的设计。
快速链接
- 安装
- 正在运行的客户端
- 向请求添加重试次数
- 使用分页的响应
- 对您的请求进行身份验证
- 处理您的响应格式
- 正确编码出站请求数据
- 处理错误的请求和响应
- 端点作为代码 < > >
按查询参数
->;可调用接受响应
和上一页参数
按URL
->;可调用接受响应
和上一页的URL
。 在按查询返回参数的情况下,可调用函数需要返回参数,或者在 url的情况。 如果响应是最后一页,则函数应返回"无"。
post(self,endpoint:str,data:dict,params:optionaldict=none)
委托post方法从端点发送数据并返回响应。
get(端点:str,参数:optionaldict=none)
委托获取从终结点获取响应的方法。
put(端点:str,数据:dict,参数:optionaldict=none)
委托Put方法发送和覆盖数据并从终结点返回响应。
修补程序(端点:str,数据:dict,参数:optionaldict=none)
委托到修补程序方法以发送和更新数据并从终结点返回响应
删除(端点:str,参数:optionaldict=none)
委托删除方法以删除位于终结点的资源。
获取请求超时->;浮点值
默认情况下,所有请求的默认超时设置为10.0秒。 是为了避免请求永远等待响应,建议 在生产应用程序中始终设置为值。但是有可能 重写此方法以返回应用程序所需的超时。
安装
pip install api-client
用法
简单示例
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
apiclient
此示例使用
get
在端点上执行get请求。
其他方法包括:post
,put
,patch
和delete
。更多
有关这些方法的信息记录在接口中
有关更复杂的用例示例,请参见:扩展示例
正在重试
为了给您的客户机添加一些健壮性,坚韧性的强大功能
已利用它向apiclient
工具包添加@retry_请求
装饰器。
这将重试任何以5xx状态代码(通常是安全的)响应的请求 当试图提出请求时,或者当 试图建立连接时会发生意外错误。
@retry_request
已配置为最多重试5分钟,呈指数级
退避策略。对于更复杂的用途,用户可以使用坚韧本身来创建
他们自己的定制装饰。
用法:
from apiclient import retry_request
class MyClient(APIClient):
@retry_request
def retry_enabled_method():
...
对于更复杂的用例,可以使用 韧性以及自定义重试策略。
例如,您可以构建一个重试修饰符,重试apiresterror
在两次重试之间等待2秒,并在5次尝试后放弃。
import tenacity
from apiclient.retrying import retry_if_api_request_error
retry_decorator = tenacity.retry(
retry=retry_if_api_request_error(),
wait=tenacity.wait_fixed(2),
stop=tenacity.stop_after_attempt(5),
reraise=True,
)
或者您可以构建一个decorator,该decorator将只在特定状态下重试。 代码(故障后)。
retry_decorator = tenacity.retry(
retry=retry_if_api_request_error(status_codes=[500, 501, 503]),
wait=tenacity.wait_fixed(2),
stop=tenacity.stop_after_attempt(5),
reraise=True,
)
分页
为了支持在发出get请求时与响应多页数据的页面联系,
在客户机方法中添加一个分页的装饰器。@paginated
可以在
页面在查询参数中指定,或通过修改URL来指定。
在这两种情况下使用都很简单;paginator decorators接受一个带有两个必需参数的callable:
用法:
from apiclient import paginated
def next_page_by_params(response, previous_page_params):
# Function reads the response data and returns the query param
# that tells the next request to go to.
return {"next": response["pages"]["next"]
def next_page_by_url(response, previous_page_url):
# Function reads the response and returns the url as string
# where the next page of data lives.
return response["pages"]["next"]["url"]
class MyClient(APIClient):
@paginated(by_query_params=next_page_by_params)
def paginated_example_one():
...
@paginated(by_url=next_page_by_url)
def paginated_example_two():
...
验证方法
身份验证方法提供了一种可以自定义 通过依赖注入实现多种身份验证方案的客户端方法: 意思是你可以改变客户的行为而不改变 基本实现。
apiclient通过指定 客户端初始化时初始化的类,如下所示:
client = ClientImplementation(
authentication_method=<AuthenticationMethodClass>(),
response_handler=...,
request_formatter=...,
)
noauthentication
这种身份验证方法不会向客户端添加任何内容, 允许API联系不强制任何身份验证的API。
示例:
client = ClientImplementation(
authentication_method=NoAuthentication(),
response_handler=...,
request_formatter=...,
)
queryparameterauthentication
此身份验证方法将相关参数和令牌添加到 客户端查询参数。用法如下:
client = ClientImplementation(
authentication_method=QueryParameterAuthentication(parameter="apikey", token="secret_token"),
response_handler=...,
request_formatter=...,
)
使用以下数据联系URL
pip install api-client
0
将向传出请求添加身份验证参数:
pip install api-client
1
头验证
此身份验证方法将相关的授权头添加到 传出的请求。用法如下:
pip install api-client
2
授权
参数和承载
方案可以通过
指定方法初始化。
pip install api-client
3
或者,当api不需要设置方案时,您可以 将其指定为计算结果为false的值,以便从 标题:
pip install api-client
4
基本验证
此身份验证方法允许指定api的用户名和密码 需要的。
pip install api-client
5
响应处理程序
响应处理程序提供了处理最终响应的标准方法
在成功请求api之后。这些必须继承自
baseresponsehandler
并实现
将接受requests.response
对象并相应地分析数据。
apiclient通过指定 客户端初始化类如下:
可以省略响应处理程序,在这种情况下,不会对 传出数据。
pip install api-client
6
请求响应处理程序
只返回原始响应的处理程序
更改。
示例:
pip install api-client
7
jsonresponsehandler
将响应数据解析为json
并返回字典的处理程序。
如果尝试解析为json时出错,则会出现一个意外错误
将被提升。
示例:
pip install api-client
8
xmlresponsehandler
将响应数据解析为xml.etree.elementtree.element
的处理程序。
如果在尝试解析为XML时出错,则会出现一个意外错误
将被提升。
示例:
pip install api-client
9
yamlresponsehandler
以yaml
格式分析响应数据并返回
字典。如果在尝试分析yaml时发生错误,则会出现意外错误
将被提升。
示例:
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
0
请求格式化程序
请求格式化程序提供了一种方式,使传出的请求数据可以 在发送前进行编码,并适当设置标题。
它们必须继承自baserequestformatter
并实现format()
方法,该方法将获取传出的数据
对象并相应地格式化
在提出请求之前。
apiclient通过指定 客户端初始化类如下:
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
1
jsonrequestformatter
将数据转换为JSON格式并添加
应用程序/json
传出请求的内容类型头。
示例:
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
2
例外情况
为api client
设计的异常处理方式使所有异常都继承自
一个基本异常类型:apiclientror
。从那以后,例外情况被分为
福尔剩余类别:
响应资源错误
尝试将成功的响应解析为定义的格式时出错。这可能是到期的
滥用responsehandler,即使用xmlresponsehandler
而不是
ajsonresponsehandler
apiresterror
提出请求时出错了。它们进一步细分为以下几类: 更大的粒度和控制。
重定向程序错误
重定向状态代码(3xx)在生成 请求。这意味着不能像我们这样将数据返回给客户机 找不到已移动的请求资源。
clienterro
联系API时返回了ClienterRor状态代码(4xx)。最常见的原因 这些错误是对客户端的误用,即向API发送错误数据。
服务器错误
发出请求时无法访问API。即5xx状态代码。
意外错误
使用客户端时发生意外错误。这通常在尝试时发生 例如,要发出请求,客户端永远不会收到响应。也可能发生 意外的状态代码(>;=600)。
端点
apiclient还提供了一种方便的方法来定义url端点
使用@endpoint
装饰符。为了用端点修饰类
修饰类必须定义一个基url
属性以及必需的
资源。decorator将把基url与资源结合起来。
示例:
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
3
扩展示例
from apiclient import APIClient
class MyClient(APIClient):
def list_customers(self):
url = "http://example.com/customers"
return self.get(url)
def add_customer(self, customer_info):
url = "http://example.com/customers"
return self.post(url, data=customer_info)
>>> client = MyClient()
>>> client.add_customer({"name": "John Smith", "age": 28})
>>> client.list_customers()
[
...,
{"name": "John Smith", "age": 28},
]
4
apiclient接口
apiclient提供以下公共接口: