How to use the requests.Session function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ztgrace / changeme / tests / changeme_tests.py View on Github external
    @responses.activate
    def test_check_basic_auth_tomcat_fail(self):
        responses.add(** mock.tomcat_fp)
        responses.add(** mock.tomcat_fp_alt)

        cred = self.get_cred(self.tomcat_name)
        assert cred['name'] == self.tomcat_name

        changeme.logger = changeme.setup_logging(False, False, None)
        s = requests.Session()
        matches = changeme.check_basic_auth(mock.tomcat_fp['url'], s, cred, self.config, False, False)
        assert len(matches) == 0
github LiuXingMing / SinaSpider / Sina_spider1 / Sina_spider1 / cookies.py View on Github external
"from": "null",
        "savestate": "30",
        "useticket": "0",
        "pagerefer": "",
        "vsnf": "1",
        "su": username,
        "service": "sso",
        "sp": password,
        "sr": "1440*900",
        "encoding": "UTF-8",
        "cdult": "3",
        "domain": "sina.com.cn",
        "prelt": "0",
        "returntype": "TEXT",
    }
    session = requests.Session()
    r = session.post(loginURL, data=postData)
    jsonStr = r.content.decode("gbk")
    info = json.loads(jsonStr)
    if info["retcode"] == "0":
        logger.warning("Get Cookie Success!( Account:%s )" % account)
        cookie = session.cookies.get_dict()
        return json.dumps(cookie)
    else:
        logger.warning("Failed!( Reason:%s )" % info["reason"])
        return ""
github KaveIO / AmbariKave / deployment / lib / kavedeploy.py View on Github external
def request_session(retries=5, backoff_factor=0.1, status_forcelist=[500, 501, 502, 503, 504, 401, 404]):
    import requests
    from requests.packages.urllib3.util.retry import Retry
    from requests.adapters import HTTPAdapter
    s = requests.Session()
    retries = Retry(total=retries,
                    backoff_factor=backoff_factor,
                    status_forcelist=status_forcelist)
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))
    return s
github databricks / databricks-cli / databricks_cli / sdk / api_client.py View on Github external
def __init__(self, user=None, password=None, host=None, token=None,
                 apiVersion=version.API_VERSION, default_headers={}, verify=True, command_name=""):
        if host[-1] == "/":
            host = host[:-1]

        self.session = requests.Session()
        self.session.mount('https://', TlsV1HttpAdapter())

        parsed_url = urlparse(host)
        scheme = parsed_url.scheme
        hostname = parsed_url.hostname
        self.url = "%s://%s/api/%s" % (scheme, hostname, apiVersion)
        if user is not None and password is not None:
            encoded_auth = (user + ":" + password).encode()
            user_header_data = "Basic " + base64.standard_b64encode(encoded_auth).decode()
            auth = {'Authorization': user_header_data, 'Content-Type': 'text/json'}
        elif token is not None:
            auth = {'Authorization': 'Bearer {}'.format(token), 'Content-Type': 'text/json'}
        else:
            auth = {}
        user_agent = {'user-agent': 'databricks-cli-{v}-{c}'.format(v=databricks_cli_version,
                                                                    c=command_name)}
github bopped / Adidas-Account-Creator / adi(3).py View on Github external
for email in \
            (GmailDotEmailGenerator(basemail + '@gmail.com').generate())[:accountstogen]:

        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
            'Accept-Encoding': 'gzip, deflate, sdch, br',
            'Accept-Language': 'en-US,en;q=0.8',
            'Upgrade-Insecure-Requests': '1'
        }
        if randompass == 'y' and 'y':
            length = 13
            chars = string.ascii_letters + string.digits + '$&@?!#%'
            random.seed = (os.urandom(1024))
            password = ''.join(random.choice(chars) for i in range(length))

        s = requests.Session()
        s.headers.update(headers)

        r = s.get('https://cp.adidas.com/web/eCom/en_AU/loadcreateaccount')
        csrftoken = BeautifulSoup(r.text, "html.parser").find('input', {'name': 'CSRFToken'}).get('value')

        s.headers.update({
            'Origin': 'https://cp.adidas.com',
            'Referer': 'https://cp.adidas.com/web/eCom/en_AU/loadcreateaccount',
        })
        r = s.post('https://cp.adidas.com/web/eCom/en_AU/accountcreate',
                   data={
                       'firstName': FirstName,
                       'lastName': LastName,
                       'day': Day,
                       'month': Month,
                       'year': Year,
github maikthulhu / GoogleMusic.bundle / Contents / Libraries / Shared / gmusicapi / session.py View on Github external
def send(self, req_kwargs, desired_auth, rsession=None):
        """Send a request from a Call using this session's auth.

        :param req_kwargs: kwargs for requests.Session.request
        :param desired_auth: protocol.shared.AuthTypes to attach
        :param rsession: (optional) a requests.Session to use
          (default ``self._rsession`` - this is exposed for test purposes)
        """
        res = None

        if not any(desired_auth):
            if rsession is None:
                # use a throwaway session to ensure it's clean
                with closing(requests.Session()) as new_session:
                    self._rsession_setup(new_session)
                    res = self._send_without_auth(req_kwargs, new_session)
            else:
                res = self._send_without_auth(req_kwargs, rsession)

        else:
            if not self.is_authenticated:
                raise NotLoggedIn

            if rsession is None:
                rsession = self._rsession

            res = self._send_with_auth(req_kwargs, desired_auth, rsession)

        return res
github openstack / cinder / cinder / zonemanager / drivers / brocade / brcd_http_fc_zone_client.py View on Github external
:param header: Request Headers

        :returns: HTTP response data
        :raises: BrocadeZoningHttpException
        """
        try:
            if header is None:
                header = {}
            header.update({"User-Agent": "OpenStack Zone Driver"})

            # Ensure only one connection is made throughout the life cycle
            protocol = zone_constant.HTTP
            if self.protocol == zone_constant.PROTOCOL_HTTPS:
                protocol = zone_constant.HTTPS
            if self.session is None:
                self.session = requests.Session()
                adapter = requests.adapters.HTTPAdapter(pool_connections=1,
                                                        pool_maxsize=1)
                self.session.mount(protocol + '://', adapter)
            url = '%s://%s%s' % (protocol, self.switch_ip, requestURL)
            response = None
            if requestType == zone_constant.GET_METHOD:
                response = self.session.get(url,
                                            headers=(header),
                                            verify=False)
            elif requestType == zone_constant.POST_METHOD:
                response = self.session.post(url,
                                             payload,
                                             headers=(header),
                                             verify=False)

            # Throw exception when response status is not OK
github tmrowco / electricitymap-contrib / parsers / lib / AU_battery.py View on Github external
def get_unit_status(unit_code, start, end, session=None):
    # nemlog_url gets generation status in 5 min intervals.

    nemlog_url = 'http://nemlog.com.au/api/unit/{}/{}/{}/json'.format(
        unit_code, start, end)

    s = session or requests.Session()
    req = s.get(nemlog_url)
    data = []
    for line in req.iter_lines(decode_unicode=True):
        data.append(line)
    try:
        latest = json.loads(data[-1])
    except IndexError:
        # No data available.
        return None

    state = float(latest["SCADAVALUE"])

    # Source classifies charge/discharge opposite to EM.
    battery_status = -1 * state

    return battery_status
github Marginal / EDMarketConnector / companion.py View on Github external
def __init__(self, cmdr):
        self.cmdr = cmdr
        self.session = requests.Session()
        self.session.headers['User-Agent'] = 'EDCD-%s-%s' % (appname, appversion)
        self.verifier = self.state = None