关于python:PyGithub认证麻烦

PyGithub authentication troubles

我正在使用带有来自 Github 的访问令牌的 PyGithub 我来到这里通过单击创建命令行工具。我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from github import Github

def readEnvironment():
    'This function reads in the environment variables form a file if needed'
    if os.path.isfile('.env') is True:
        with open('.env', 'r') as file:
            for line in file:
                if line.startswith('#'):
                    continue
                # Remove leading `export `
                # then, split name / value pair
                key, value = line.split('=', 1)
                os.environ[key] = value

@click.group()
def cli():
    pass


@click.command()
@click.option('--token', default=None, help='The Github access token', prompt=False)
def github(token):
    if None == token and (None != os.environ['GITHUB_ACCESS_TOKEN'] or '' != os.environ['GITHUB_ACCESS_TOKEN']):
        token = os.environ['GITHUB_ACCESS_TOKEN']
    client = Github(token)
    print(client)

    # Then play with your Github objects:
    for repo in client.get_user().get_repos():
        print(repo.name)

cli.add_command(github)

if __name__ == '__main__':
    readEnvironment()
    cli()

但我收到以下错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Traceback (most recent call last):
  File"farley.py", line 142, in <module>
    cli()
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File"farley.py", line 73, in github
    user = client.get_user(token)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/MainClass.py", line 264, in get_user
   "GET","/users/" + login
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/Requester.py", line 322, in requestJsonAndCheck
    verb, url, parameters, headers, input, self.__customConnection(url)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/Requester.py", line 413, in requestJson
    return self.__requestEncode(cnx, verb, url, parameters, headers, input, encode)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/Requester.py", line 475, in __requestEncode
    cnx, verb, url, requestHeaders, encoded_input
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/Requester.py", line 501, in __requestRaw
    response = cnx.getresponse()
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/github/Requester.py", line 119, in getresponse
    allow_redirects=False,
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 546, in get
    return self.request('GET', url, **kwargs)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connectionpool.py", line 387, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1270, in _send_request
    self.putheader(hdr, value)
  File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1207, in putheader
    raise ValueError('Invalid header value %r' % (values[i],))
ValueError: Invalid header value b'token `omitted`\
'

其中 omitted 是我从 Github 获得的访问令牌。正确的标记出现在错误中。这是 PyGithub 文档中给出的基本示例,所以我不确定我错过了什么。当我在 click 方法之外运行代码时,它工作正常。我正在使用 Python 3.7.2 和 PyGithub 1.45 并单击 7.0.


原来错误信息中的\
是关键。我在没有删除换行符的情况下读取环境变量。我将功能固定为

1
2
3
4
5
6
7
8
9
10
11
def readEnvironment():
    'This function reads in the environment variables form a file if needed'
    if os.path.isfile('.env') is True:
        with open('.env', 'r') as file:
            for line in file:
                if line.startswith('#'):
                    continue
                # Remove leading `export `
                # then, split name / value pair
                key, value = line.split('=', 1)
                os.environ[key] = value[:-1]

然后一切正常。


您可能想使用 Click 的内置 envvar 支持,并可能转换为字符串?

1
2
3
4
5
6
7
@click.command()
@click.option('--token', required=True, help='The Github access token', envvar='GITHUB_ACCESS_TOKEN')
def github(token):
    client = Github(str(token))
    print(client)
    for repo in client.get_user().get_repos():
        print(repo.name)