Python requests.sessions.Session() Examples

The following are 16 code examples of requests.sessions.Session(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.sessions , or try the search function .
Example #1
Source File: networking.py    From dephell with MIT License 7 votes vote down vote up
def requests_session(*, auth: Optional[Any] = None, headers: Optional[Any] = None, **kwargs: Any) -> Session:
    session = requests.Session()
    if auth:
        session.auth = auth

    # setup SSL
    cafile = config.get('ca')
    if cafile:
        session.verify = cafile

    # set headers
    if headers is None:
        headers = dict()
    headers.setdefault('User-Agent', USER_AGENT)
    session.headers = headers
    if kwargs:
        session.__dict__.update(kwargs)

    return session 
Example #2
Source File: utils.py    From oauth-pythonclient with Apache License 2.0 6 votes vote down vote up
def get_discovery_doc(environment, session=None):
    """Gets discovery doc based on environment specified.
    
    :param environment: App environment, accepted values: 'sandbox','production','prod','e2e'
    :param session: `requests.Session` object if a session is already being used, defaults to None
    :return: Discovery doc response 
    :raises HTTPError: if response status != 200
    """

    if environment.lower() in ['production', 'prod']:
        discovery_url = DISCOVERY_URL['production']
    else:
        discovery_url = DISCOVERY_URL['sandbox']
    

    response = requests.get(url=discovery_url, headers={'User-Agent': 'Mozilla/5.0'})
        
    if response.status_code != 200:
        raise AuthClientError(response)
    return response.json() 
Example #3
Source File: core.py    From requests-racer with GNU General Public License v3.0 6 votes vote down vote up
def from_requests_session(cls, other):
        """Creates a `SynchronizedSession` from the provided `requests.Session`
        object. Does not modify the original object, but does not perform a
        deep copy either, so modifications to the returned
        `SynchronizedSession` might affect the original session object as well,
        and vice versa.
        """
        # this is a moderate HACK:
        # we use __getstate__() and __setstate__(), intended to help pickle
        # sessions, to get all of the state of the provided session and add
        # it to the new one, throwing away the adapters since we don't want
        # those to be overwritten.
        # the output of __getstate__() is supposed to be an opaque blob that
        # you aren't really supposed to inspect or modify, so this relies on
        # specifics of the implementation of requests.Session that are not
        # guaranteed to be stable.
        session_state = other.__getstate__()

        if 'adapters' in session_state:
            del session_state['adapters']

        new_session = cls()
        new_session.__setstate__(session_state)

        return new_session 
Example #4
Source File: client.py    From intrinio with MIT License 6 votes vote down vote up
def _web_request(url, parameters):
    """
    Perform HTTP GET request and return response.

    Args:
        url: Absolute URL
        parameters: URL parameters

    Returns:
        Response as a string
    """
    auth = (username, password)

    with sessions.Session() as session:
        response = session.request('GET', url, params=parameters, auth=auth,
                                   verify=True)
    if not response.ok:
        response.raise_for_status()

    return response.content.decode('utf-8') 
Example #5
Source File: __init__.py    From splitwise with MIT License 5 votes vote down vote up
def __makeRequest(self, url, method="GET", data=None, auth=None):

        if auth is None and self.auth:
            auth = self.auth

        requestObj = Request(method=method, url=url, data=data, auth=auth)

        prep_req = requestObj.prepare()

        with sessions.Session() as session:
            response = session.send(prep_req)

        if response.status_code == 200:
            if (response.content and hasattr(response.content, "decode")):
                return response.content.decode("utf-8")
            return response.content

        if response.status_code == 401:
            raise SplitwiseUnauthorizedException("Please check your token or consumer id and secret", response=response)

        if response.status_code == 403:
            raise SplitwiseNotAllowedException("You are not allowed to perform this operation", response=response)

        if response.status_code == 400:
            raise SplitwiseBadRequestException("Please check your request", response=response)

        if response.status_code == 404:
            raise SplitwiseNotFoundException("Required resource is not found", response)

        raise SplitwiseException("Unknown error happened", response) 
Example #6
Source File: test_api_client.py    From coinbase-commerce-python with Apache License 2.0 5 votes vote down vote up
def test_init(self):
        api_key, base_url, api_version = TestApiClient.mock_client_params()
        client = Client(api_key, base_url, api_version)
        self.assertEqual(client.API_VERSION, api_version)
        self.assertEqual(client.BASE_API_URI, base_url)
        self.assertIsInstance(client.session, Session) 
Example #7
Source File: utils.py    From oauth-pythonclient with Apache License 2.0 5 votes vote down vote up
def send_request(method, url, header, obj, body=None, session=None, oauth1_header=None):
    """Makes API request using requests library, raises `intuitlib.exceptions.AuthClientError` if request not successful and sets specified object attributes from API response if request successful
    
    :param method: HTTP method type
    :param url: request URL
    :param header: request headers
    :param obj: object to set the attributes to
    :param body: request body, defaults to None
    :param session: requests session, defaults to None
    :param oauth1_header: OAuth1 auth header, defaults to None
    :raises AuthClientError: In case response != 200
    :return: requests object
    """

    headers = ACCEPT_HEADER
    header.update(headers)

    if session is not None and isinstance(session, Session):
        response = session.request(method, url, headers=header, data=body, auth=oauth1_header)
    else:
        response = requests.request(method, url, headers=header, data=body, auth=oauth1_header) 

    if response.status_code != 200:
        raise AuthClientError(response)

    if response.content:
        set_attributes(obj, response.json())

    return response 
Example #8
Source File: client.py    From networking-odl with Apache License 2.0 5 votes vote down vote up
def __init__(self, url, username, password, timeout):
        super(OpenDaylightRestClient, self).__init__()
        self.url = url
        self.timeout = timeout
        self.session = sessions.Session()
        self.session.auth = (username, password) 
Example #9
Source File: CTFDump.py    From CTFDump with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, url):
        self.url = url
        self.session = Session()
        self.logger = logging.getLogger(__name__) 
Example #10
Source File: vmrayclient.py    From Cortex-Analyzers with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, url, key, cert=True, reanalyze=True):
        self.url = url
        self.key = key
        if cert and os.path.isfile(cert):
            self.cert = cert
        else:
            self.cert = False
        self.reanalyze = reanalyze
        self.headers = self._prepare_headers()
        self.session = sessions.Session()
        self.session.headers = self.headers
        self.session.verify = self.cert 
Example #11
Source File: api.py    From pithy-test with Apache License 2.0 5 votes vote down vote up
def create_session(self):
        """
        如果接收到的要变参数中有session,且为Session对象,赋值给session变量, 否则创建一个
        """
        if self.is_class:
            self.session = getattr(self.func_im_self, 'session', None)
            if not isinstance(self.session, Session):
                session = Session()
                setattr(self.func_im_self, 'session', session)
                self.session = session

        elif isinstance(self.func_return.get('session'), Session):
            self.session = self.func_return.get('session')
        else:
            self.session = Session() 
Example #12
Source File: api.py    From pithy-test with Apache License 2.0 5 votes vote down vote up
def make_session():
    return Session() 
Example #13
Source File: putclient.py    From collectd-cloudwatch with MIT License 5 votes vote down vote up
def _prepare_session(self):
        self.session = Session()
        if self.proxy_server_name is not None:
            proxy_server = self.proxy_server_name
            self._LOGGER.info("Using proxy server: " + proxy_server)
            if self.proxy_server_port is not None:
                proxy_server = proxy_server + ":" + self.proxy_server_port
                self._LOGGER.info("Using proxy server port: " + self.proxy_server_port)
            proxies = {'https': proxy_server}
            self.session.proxies.update(proxies)
        else:
            self._LOGGER.info("No proxy server is in use")
        self.session.mount("http://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
        self.session.mount("https://", HTTPAdapter(max_retries=self._TOTAL_RETRIES)) 
Example #14
Source File: ec2getclient.py    From collectd-cloudwatch with MIT License 5 votes vote down vote up
def _run_request(self, request):
        """
        Executes HTTP GET request with timeout using the endpoint defined upon client creation.
        """
        session = Session()
        session.mount("http://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
        session.mount("https://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
        result = session.get(self.endpoint + "?" + request, headers=self._get_custom_headers(), timeout=self.timeout)
        result.raise_for_status()
        return result 
Example #15
Source File: _internal.py    From nexmo-python with MIT License 5 votes vote down vote up
def __init__(self, host, user_agent, api_key, api_secret, timeout=None):
        self._host = host
        self._session = session = Session()
        self.timeout = None
        session.auth = (api_key, api_secret)  # Basic authentication.
        session.headers.update({"User-Agent": user_agent}) 
Example #16
Source File: test_gcp_cloud_functions_sandbox_and_screenshot_webpage.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def test_success(self, circuits_app, gcp_url, expected_results):
        """ Test calling with sample values for the parameters """
        function_params = {
            "gcp_url": gcp_url
        }
        # Mock acquiring the config options, all config options are set to '10' or 10
        with patch.object(GCPHelper, "get_config_option", lambda x, y, z=None: "10", True):
            # Get a handle on the requests.Session class and patch its get function
            with patch.object(Session, 'get') as mock_session:
                # Replace the return value of our mock_session with a custom function
                mock_session.return_value = mocked_requests_get(success=True)
                # Fire the function with mocked functionality
                results = call_gcp_cloud_functions_sandbox_and_screenshot_webpage_function(circuits_app, function_params)
                assert (expected_results["success"] == results["success"])