PyGithub authentication troubles

I am using PyGithub with an access token from Github I got here to create a command line tool with click. My code is as follows:

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()

but I get the following error

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`\n'

where omitted is the access token I got from Github. The correct token appears in the error. This is the basic example given in the PyGithub docs, so I'm unsure what I am missing. When I run the code outside of a click method it works fine. I'm using Python 3.7.2 and PyGithub 1.45 and Click 7.0.

Answers

It turns out that \n in the error message was key. I was reading in the environment variables without removing the newline character. I fixed the function to

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]

and then everything worked fine.

Posted on by wogsland