用Python实现Github-API

2024-09-27 09:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

来自视图.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的存储库列表。在

我怎么才能做到呢?在

请帮帮我!在

提前谢谢!在


Tags: 项目pytoken视图apijsonsearchget
1条回答
网友
1楼 · 发布于 2024-09-27 09:31:55

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

但是开发人员给它附加了一些方便的函数,例如将答案作为JSON对象来解释。response对象有一个.json()函数,其目的是将内容解释为JSON字符串,并返回其对应的普通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})

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

相关问题 更多 >

    热门问题