包装web api变得很容易。
tortilla的Python项目详细描述
很容易包装web api。
通过PIP安装:
pip install tortilla
快速使用概述:
>>>importtortilla>>>github=tortilla.wrap('https://api.github.com')>>>user=github.users.get('octocat')>>>user.locationu'San Francisco'
基本知识
玉米饼用一点魔法来包装原料药。每当你接到或打电话给 包装器的属性,url将附加该属性的名称或 方法参数。假设我们有以下代码:
id,count=71,20api=tortilla.wrap('https://api.example.org')api.video(id).comments.get(count)
每个属性和方法调用都代表url的一部分:
api -> https://api.example.org .video -> /video (id) -> /71 .comments -> /comments .get(count) -> /20 Final URL -> https://api.example.org/video/71/comments/20
链的最后一部分(.get())执行请求。它也 (可选)将最后一部分附加到URL这样你就可以 像这样的东西:
api.video.get(id)# instead of thisapi.video(id).get()
总之,获取属性用于定义 URL和调用它们用于定义URL的动态部分
一旦你把所有的东西都拴在一起,玉米饼就会 为您请求并解析响应。
目前,Tortilla只接受JSON格式的响应。 支持更多格式是未来玉米饼版本的发展方向。
解析后的响应将是bunchified这将生成字典键 可通过属性访问。假设我们得到以下json 用户“john”的响应:
{"name":"John Doe"}
如果我们用已经创建的包装器请求这个,我们可以访问 通过属性的响应数据:
>>>user=api.users.get('john')>>>user.nameu'John Doe'
标题
访问api的一个常见需求是提供身份验证 数据。这通常必须在每个请求的头中描述。 Tortilla让你很容易描述那些重复出现的标题:
api.config.headers.token='secret authentication token'
还可以为每个请求定义自定义头:
api.endpoint.get(headers={'this':'that'})
这些报头将附加到包装器的现有报头中。
参数
可以在params选项中为每个请求定义URL参数:
api.search.get(params={'q':'search query'})
缓存
有些api对您可以发出的请求数量有限制。在这些 在案例中,缓存非常有用。你可以用 cache_lifetime参数:
api=tortilla.wrap('https://api.example.org',cache_lifetime=100)
这个包装器上的所有请求现在都将被缓存100 几秒钟如果要在特定情况下忽略缓存,则 可以使用ignore_cache参数:
api.special.request.get(ignore_cache=True)
现在将重新加载响应
URL扩展名
像Twitter这样的api需要在URL中指定 响应格式这可以在extension参数中定义:
api=tortilla.wrap('https://api.twitter.com/1.1',extension='json')
此选项可被每个请求或子包装覆盖:
api.special.endpoint.extension='xml'api.special.endpoint.get(extension='xml')
URL后缀
有些api在url的末尾使用斜杠,如下面的示例:
https://api.example.org/resource/
包装时,可以添加带suffix="/"参数的尾随斜杠 api或使用.url(suffix="/")方法获取url:
api=tortilla.wrap('https://api.example.org',suffix="/")api.video(71).comments.url()
将返回以下URL:
api -> https://api.example.org .video -> /video (id) -> /71/ Final URL -> https://api.example.org/video/71/
调试
激活调试模式可以使用debug参数来完成:
api.debug=True# ORapi=tortilla.wrap('https://api.example.org',debug=True)
您可以覆盖每个请求的debug参数:
api.stuff.get(debug=False)api.other.stuff.get(debug=True)
使用GitHub API的示例:
>>>user=github.users.get('octocat')ExecutingGETrequest:URL:https://api.github.com/users/octocatheaders:{}query:Nonedata:NoneGot200OK:{u'public_repos':5,u'site_admin':...
享受您的数据。