OAuth-客户机
alf的Python项目详细描述
python oauth 2客户端
alf是基于requests.Session的oauth 2客户机 对Client Credentials Flow的无缝支持。
功能
- 自动令牌检索和续订
- 令牌过期控制
- 自动令牌存储
- 自动重试状态401(未授权)
用法
初始化客户端并将其用作requests.Session 反对。
fromalf.clientimportClientalf=Client(token_endpoint='http://example.com/token',client_id='client-id',client_secret='secret')resource_uri='http://example.com/resource'alf.put(resource_uri,data='{"name": "alf"}',headers={'Content-Type':'application/json'})alf.get(resource_uri)alf.delete(resource_uri)
使用自定义令牌存储
现在传递带有get和set属性的对象,您可以存储或检索令牌。
此对象可以是redis、memcache或自定义对象。
fromalf.clientimportClientfromredisimportStrictRedisredis=StrictRedis(host='localhost',port=6379,db=0)alf=Client(token_endpoint='http://example.com/token',client_id='client-id',client_secret='secret',token_storage=redis)resource_uri='http://example.com/resource'alf.put(resource_uri,data='{"name": "alf"}',headers={'Content-Type':'application/json'})alf.get(resource_uri)alf.delete(resource_uri)
它是如何工作的?
在请求之前,将在身份验证终结点上请求令牌 带有access_token和expires_in键的json响应将是 预期。
如果出现以下情况,则在端点的错误响应之后将发出多次尝试 使用了token_retries参数。查看token-retrying了解更多信息。
alf根据^{tt2}保存令牌,直到它过期$ 价值。
令牌将用于 最初的请求。
GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer token-12312
如果请求以401(未授权)状态失败,则检索新令牌 从终结点重试请求。只有一次,如果 再次失败返回错误响应。
令牌将对以下每个请求重复使用,直到它过期。
令牌重试
客户端支持retry interface from urllib3来重复尝试 从终结点检索令牌。
当响应状态为 是500,每次出错后它将再等待0.3秒(称为 backoff)。
fromrequests.packages.urllib3.utilimportRetryfromalf.clientimportClientalf=Client(token_endpoint='http://example.com/token',client_id='client-id',client_secret='secret',token_retry=Retry(total=5,status_forcelist=[500],backoff_factor=0.3))
工作流程
故障排除
如果检索令牌时出错,将返回错误响应, 真正的要求不会发生。