apiwrappers是一个用于构建同时使用常规和异步代码的API客户端的库
apiwrappers的Python项目详细描述
apiwrappers是一个用于构建API客户端的库 它同时适用于常规和异步代码。在
特点
安装
pip install 'apiwrappers[aiohttp,requests]'
注意:附加功能主要用于API客户端的最终用户
快速启动
提出请求相当简单:
^{pr2}$编写一个简单的API客户端
使用apiwrappers可以为不同的API引导客户机 很快很容易。在
下面是典型的API客户端的外观:
from__future__importannotationsfromdataclassesimportdataclassfromtypingimportAwaitable,Generic,List,TypeVar,overloadfromapiwrappersimportAsyncDriver,Driver,Request,Url,fetchT=TypeVar("T",Driver,AsyncDriver)@dataclassclassRepo:id:intname:strclassGitHub(Generic[T]):def__init__(self,host:str,driver:T):self.url=Url(host)self.driver:T=driver@overloaddefget_repos(self:Github[Driver],username:str)->List[Repo]:...@overloaddefget_repos(self:Github[AsyncDriver],username:str)->Awaitable[List[Repo]]:...defget_repos(self,username:str):url=self.url("/users/{username}/repos",username=username)request=Request("GET",url)returnfetch(self.driver,request,model=List[Repo])
这是一个小型的,但完全类型化的API客户机 api.github.com获取所有用户repo的端点 按用户名:
这里我们定义了Repodataclass来描述我们想要的 从response获取并将其传递给fetch函数。 fetch然后将发出一个请求并对该类型强制转换响应。在
请注意我们如何创建URL:
url=self.url("/users/{username}/repos",username=username)
例如,有一个有用的模板,例如 或者用于聚合度量,所以我们不立即格式化 提供模板和替换字段。在
使用API客户端
以下是我们如何使用它:
>>>fromapiwrappersimportmake_driver>>>driver=make_driver("requests")>>>github=GitHub("https://api.github.com",driver=driver)>>>github.get_repos("unmade")[Repo(id=47463599,name='am-date-picker'),Repo(id=231653904,name='apiwrappers'),Repo(id=144204778,name='conway'),...]
要在asyncio中使用它,我们需要做的就是提供一个合适的驱动程序 别忘了await方法调用:
使用IPython或python3.8+和Python-m asyncio
以_交互_方式_尝试_此_代码_ <_eem_>_
>>>fromapiwrappersimportmake_driver>>>driver=make_driver("aiohttp")>>>github=GitHub("https://api.github.com",driver=driver)>>>awaitgithub.get_repos("unmade")[Repo(id=47463599,name='am-date-picker'),Repo(id=231653904,name='apiwrappers'),Repo(id=144204778,name='conway'),...]
- 项目
标签: