如何在python中使用github api令牌进行请求 [英] how to use github api token in python for requesting

查看:279
本文介绍了如何在python中使用github api令牌进行请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用用户名和密码在python中获取Github api令牌,但是我无法使用该API令牌来请求任何POST/DELETE/PATCH.

I'm able to obtain Github api token in python using username and password but i'm not able to use that API-Token for requesting any POST/DELETE/PATCH.

我们如何使用Github API令牌进行任何请求. 例如,我有API令牌,说"hbnajkjanjknjknh23b2jk2kj2jnkl2 ..."

How do we use Github API-Tokens for making any request. For eg, i have API-Token lets say 'hbnajkjanjknjknh23b2jk2kj2jnkl2...'

现在可以请求

#i'm providing username and API-Token in headers like    
self.header = {'X-Github-Username': self.username,
               'X-Github-API-Token': self.api_token                  
              }
#then requesting(post) to create a gist
r = requests.post(url, headers=headers)

但是我总是收到401 errorBad Crediantials消息.

But i'm always getting 401 error with Bad Crediantials message.

在不输入密码的情况下使用API​​令牌的正确方法是什么

What's the proper way to use API-Tokens without inputting the password

推荐答案

对于一个,我建议对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.

这篇关于如何在python中使用github api令牌进行请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆