python - 在 Python 中实现 Github API

标签 python django python-requests github-api

我正在使用 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 的存储库列表。

我怎样才能做到这一点?

请帮帮我!

提前致谢!

最佳答案

如果您执行 .get(..).post(. .) 或类似的东西。由于响应可能非常大(数百行),默认情况下它不会打印内容。

但是开发人员为其附加了一些方便的功能,例如将答案插入为 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'
        <b>response</b> = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
        <b>login = response.json()</b>  # obtain the payload as JSON object
        print(login)
        return render(request, 'navigator/template.html', {'login': login})

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

关于python - 在 Python 中实现 Github API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492241/

相关文章:

python - 套接字绑定(bind)是什么意思?

python - 是否有 django 应用程序为服务器上的文件提供文件选择器?

django - 如何将自定义 css 类添加到 django-filters 字段

python - 为什么 python requests.get() 的默认超时对于不同的机器不同

python-2.7 - 尝试使用 python 请求模块发出发布请求时出现 http 500 错误

python - 进度条在 Python 中无法正常工作

python - Python 的按位求补运算符 (~ 代字号) 是如何工作的?

python - 加快修改数组的 numpy 数组的循环速度

Python:使用负函数比较元胞数组

mysql - 如何在 mysql 中使用 django 的 manage.py sql* 命令