钻取信息直接访问API Python客户端
directaccess的Python项目详细描述
直接访问py
钻研信息的直接访问api的薄包装。处理身份验证和令牌管理、分页和 网络相关错误处理/重试。
这个模块是在Python3.6上构建和测试的,但是应该在Python2.7和更高版本上工作。
安装
pip install directaccess
用法
直接访问版本1
对于API的版本1,创建DirectAccessv1类的实例并为其提供API密钥
fromdirectaccessimportDirectAccessV1d1=DirectAccessV1(api_key='<your-api-key>')
将数据集作为第一个参数提供给查询方法,将任何查询参数作为关键字参数提供给查询方法。 请参阅直接访问文档中的有效数据集名称和查询参数。 query方法以dict的形式返回api响应的生成器。
forrowind1.query('legal-leases',county_parish='Reeves',state_province='TX',min_expiration_date='2018-06-01'):print(row)
直接访问版本2
对于API的版本2,创建DirectAccessv2类的实例,为其提供API密钥、客户端ID和客户端机密。 返回的访问令牌将作为实例(d2.access_令牌)和授权的属性提供 标题自动设置
fromdirectaccessimportDirectAccessV2d2=DirectAccessV2(api_key='<your-api-key>',client_id='<your-client-id>',client_secret='<your-client-secret>',)
与v1类一样,为查询方法提供数据集和查询参数。所有查询参数必须与有效的 在直接访问文档中找到并作为关键字参数传递的参数。
forrowind2.query('well-origins',county='REEVES',pagesize=10000):print(row)
过滤功能
直接访问版本2支持过滤功能。这些可以作为关键字参数的字符串传递。
一些常见的过滤器大于(gt()
)、小于(lt()
)、为空、不为空(not(null)
)以及介于(btw()
)之间。
有关所有可用筛选器的列表,请参阅直接访问文档。
# Get well records updated after 2018-08-01 and without deleted datesforrowind2.query('well-origins',updateddate='gt(2018-08-01)',deleteddate='null'):print(row)# Get permit records with approved dates between 2018-03-01 and 2018-06-01forrowind2.query('permits',approveddate='btw(2018-03-01,2018-06-01)'):print(row)
您可以使用fields
关键字来限制请求中返回的字段。
forrowind2.query('rigs',fields='DrillType,LeaseName,PermitDepth'):print(row)
逃逸
当发出包含某些字符(如逗号)的请求时,请使用反斜杠对其进行转义。
# Escaping the comma before LLCforrowind2.query('producing-entities',curropername='PERCUSSION PETROLEUM OPERATING\, LLC'):print(row)
错误
直接访问是一个数据api,根据您的订阅,它有数亿条记录。网络天生就不可靠 错误会在某个时刻发生。本模块提供两种处理错误的方法; 具有指数退避的可配置重试(可用于v1和v2),并公开分页 链接为属性(仅v2)。
请求时重试
fromdirectaccessimportDirectAccessV1# Retry 5 times, backing off exponentially # (1 second, 2 seconds, 4 seconds, 16 seconds, 256 seconds)d1=DirectAccessV1(api_key='<your-api-key>',retries=5,backoff_factor=1)
如果出现不可恢复的错误,您可以以保持分页链接的方式编写进程。 这样你就可以回到你离开的地方。基本实现可能如下:
importosimportjsonfromdirectaccessimportDirectAccessV2RECOVERY_FILE='your-api-links.json'd2=DirectAccessV2(api_key='<your-api-key>',client_id='<your-client-id>',client_secret='<your-client-secret>',retries=5,backoff_factor=1)# if there's an existing recovery file, provide it to the instanceifos.path.exists(RECOVERY_FILE):withopen(RECOVERY_FILE)asf:d2.links=json.loads(f.read())# interact with the api, writing out a recovery file in the event of an unrecoverable error. # this will overwrite any previously existing file.try:forrowind2.query('permits'):print(row)exceptException:withopen(RECOVERY_FILE,mode='w')asf:f.write(json.dumps(d2.links))
您可以以任何方式持久化分页链接。如果提供了directaccessv2类,则需要类似于 从Requests module's links提供的那个 上面的json示例只是实现这一点的一种方法。