【问题标题】:Implement Github API in Python在 Python 中实现 Github API
【发布时间】:2018-11-02 16:07:17
【问题描述】:

我正在使用 Python(3.6) 开发一个项目,我需要在其中实现 GitHub API。 我尝试过使用 JSON api:

来自views.py:

class GhNavigator(CreateView):
    def get(self, request, *args, **kwargs):
        term = request.GET.get('search_term')
        username = 'arycloud'
        token = 'API_TOKEN'
        login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
        print(login)
        return render(request, 'navigator/template.html', {'login': login})

但它只是返回status 200,我想获取用户传递的term 的存储库列表。

我怎样才能做到这一点?

请帮帮我!

提前致谢!

【问题讨论】:

  • 打印什么?你有什么要求?您可能应该调用login.json 来获取其中包含的内容。
  • 当我打印 login.json 它返回 <bound method Response.json of <Response [200]>>
  • .json 是一个函数,所以你应该调用它(即login.json())。
  • 它是否也包含提交?
  • 这取决于 API 的使用方式。我认为您应该检查 GitHub API 文档。但是我自己的一个快速实验,并没有立即产生提交。

标签: python django python-requests github-api


【解决方案1】:

如果您执行 .get(..).post(..) 或类似的操作,requests 库将返回 Response 对象。由于响应可能非常庞大(数百行),默认情况下它不会打印内容。

但开发人员为其附加了一些方便的功能,例如将答案解释为 JSON 对象。响应对象有一个 .json() 函数,旨在将内容解释为 JSON 字符串,并返回其 Vanilla Python 对应项。

因此,您可以通过调用.json(..) 来访问响应(并以您想要的方式呈现它):

class GhNavigator(CreateView):
    def get(self, request, *args, **kwargs):
        term = request.GET.get('search_term')
        username = 'arycloud'
        token = 'API_TOKEN'
        response = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
        login = response.json()  # obtain the payload as JSON object
        print(login)
        return render(request, 'navigator/template.html', {'login': login})

当然,现在由您来根据您的特定“业务逻辑”解释该对象,并呈现您认为包含所需信息的页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 2016-12-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多