我正在使用 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/