File: session.py

package info (click to toggle)
python-coverage 7.8.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,188 kB
  • sloc: python: 31,123; ansic: 1,184; javascript: 773; makefile: 304; sh: 107; xml: 48
file content (32 lines) | stat: -rw-r--r-- 924 bytes parent folder | download
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
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt

"""Help make a requests Session with proper authentication."""

import os
import sys

import requests

_SESSIONS = {}

def get_session(env="GITHUB_TOKEN"):
    """Get a properly authenticated requests Session.

    Get the token from the `env` environment variable.
    """

    session = _SESSIONS.get(env)
    if session is None:
        token = os.environ.get(env)
        if token is None:
            sys.exit(f"!! Must have {env}")

        session = requests.session()
        session.headers["Authorization"] = f"token {token}"
        # requests.get() will always prefer the .netrc file even if a header
        # is already set.  This tells it to ignore the .netrc file.
        session.trust_env = False
        _SESSIONS[env] = session

    return session