且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中使用github api令牌进行请求

更新时间:2022-05-01 00:10:55

首先,我建议为 API 使用包装器.您在这里提出了很多问题,可以通过找到您欣赏其 API 的包装器来简化这些问题.有一个用 Python 编写的包装器列表这里.

For one, I would recommend using a wrapper for the API. You're asking a lot of questions on here that could be simplified by finding a wrapper whose API you appreciate. There's a list of wrappers written in Python here.

至于您实际回答您的问题,GitHub 文档相当清楚您需要发送授权标头.你的电话实际上看起来像这样:

As for your actually answering your question, the GitHub documentation is fairly clear that you need to send the Authorization header. Your call would actually look like this:

self.headers = {'Authorization': 'token %s' % self.api_token}
r = requests.post(url, headers=self.headers)

既然您似乎在使用请求和类,那么我可以大胆地提出建议吗?假设您正在做一些事情,比如为 API 制作一个客户端.您可能有这样的课程:

Since it seems like you're using requests and a class, might I be so bold as to make a recommendation? Let's say you're doing something like making a client for the API. You might have a class like so:

class GitHub(object):
    def __init__(self, **config_options):
        self.__dict__.update(**config_options)
        self.session = requests.Session()
        if hasattr(self, 'api_token'):
           self.session.headers['Authorization'] = 'token %s' % self.api_token
        elif hasattr(self, 'username') and hasattr(self, 'password'):
           self.session.auth = (self.username, self.password)

    def call_to_the_api(self, *args):
        # do stuff with args
        return self.session.post(url)

Session 对象将为您处理身份验证(通过令牌或用户名和密码组合).

The Session object will take care of the authentication for you (either by the tokens or username and password combination).

此外,如果您最终决定使用 github3.py 来满足您的 API 包装器需求,这里有一个标签.

Also, if you end up deciding to use github3.py for your API wrapper needs, there's a tag on here for it.