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

查看:48
本文介绍了如何在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-Tokens 发出任何请求.例如,我有 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)

但我总是收到带有 Bad Credentials 消息的 401 错误.

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

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

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

推荐答案

首先,我建议为 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.

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

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