在 Python 中实施 Github API
Implement Github API in Python
我正在使用 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})
但它只是 returns status 200
,我想获取用户传递的 term
的存储库列表。
我怎样才能做到这一点?
请帮帮我!
提前致谢!
如果您执行 .get(..)
、.post(..)
或类似操作,requests
库将 return 一个 Response
对象。由于响应可能非常大(数百行),默认情况下它不会打印内容。
但开发人员为其附加了一些方便的功能,例如将答案插入 JSON 对象。响应对象有一个 .json()
函数,旨在将内容解释为 JSON 字符串,return 是它的 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})
当然,现在由您根据您的特定 "business logic" 解释该对象,并呈现您认为包含所需信息的页面。
我正在使用 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})
但它只是 returns status 200
,我想获取用户传递的 term
的存储库列表。
我怎样才能做到这一点?
请帮帮我!
提前致谢!
如果您执行 .get(..)
、.post(..)
或类似操作,requests
库将 return 一个 Response
对象。由于响应可能非常大(数百行),默认情况下它不会打印内容。
但开发人员为其附加了一些方便的功能,例如将答案插入 JSON 对象。响应对象有一个 .json()
函数,旨在将内容解释为 JSON 字符串,return 是它的 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})
当然,现在由您根据您的特定 "business logic" 解释该对象,并呈现您认为包含所需信息的页面。