且构网

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

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

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

对于一个,我建议对API使用包装器.您在这里提出了很多问题,可以通过找到您喜欢其API的包装器来简化这些问题. 此处.

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文档非常清楚,您需要发送 Authorization标头 .您的通话实际上看起来像这样:

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.