當前位置: 首頁>>代碼示例>>Python>>正文


Python sessions.Session方法代碼示例

本文整理匯總了Python中requests.sessions.Session方法的典型用法代碼示例。如果您正苦於以下問題:Python sessions.Session方法的具體用法?Python sessions.Session怎麽用?Python sessions.Session使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在requests.sessions的用法示例。


在下文中一共展示了sessions.Session方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: requests_session

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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 
開發者ID:dephell,項目名稱:dephell,代碼行數:21,代碼來源:networking.py

示例2: get_discovery_doc

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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() 
開發者ID:intuit,項目名稱:oauth-pythonclient,代碼行數:22,代碼來源:utils.py

示例3: from_requests_session

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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 
開發者ID:nccgroup,項目名稱:requests-racer,代碼行數:27,代碼來源:core.py

示例4: _web_request

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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') 
開發者ID:nhedlund,項目名稱:intrinio,代碼行數:22,代碼來源:client.py

示例5: __makeRequest

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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) 
開發者ID:namaggarwal,項目名稱:splitwise,代碼行數:32,代碼來源:__init__.py

示例6: test_init

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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) 
開發者ID:coinbase,項目名稱:coinbase-commerce-python,代碼行數:8,代碼來源:test_api_client.py

示例7: send_request

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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 
開發者ID:intuit,項目名稱:oauth-pythonclient,代碼行數:31,代碼來源:utils.py

示例8: __init__

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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) 
開發者ID:openstack,項目名稱:networking-odl,代碼行數:8,代碼來源:client.py

示例9: __init__

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
def __init__(self, url):
        self.url = url
        self.session = Session()
        self.logger = logging.getLogger(__name__) 
開發者ID:realgam3,項目名稱:CTFDump,代碼行數:6,代碼來源:CTFDump.py

示例10: __init__

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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 
開發者ID:TheHive-Project,項目名稱:Cortex-Analyzers,代碼行數:14,代碼來源:vmrayclient.py

示例11: create_session

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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() 
開發者ID:yuyu1987,項目名稱:pithy-test,代碼行數:17,代碼來源:api.py

示例12: make_session

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
def make_session():
    return Session() 
開發者ID:yuyu1987,項目名稱:pithy-test,代碼行數:4,代碼來源:api.py

示例13: _prepare_session

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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)) 
開發者ID:awslabs,項目名稱:collectd-cloudwatch,代碼行數:16,代碼來源:putclient.py

示例14: _run_request

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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 
開發者ID:awslabs,項目名稱:collectd-cloudwatch,代碼行數:12,代碼來源:ec2getclient.py

示例15: __init__

# 需要導入模塊: from requests import sessions [as 別名]
# 或者: from requests.sessions import Session [as 別名]
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}) 
開發者ID:Nexmo,項目名稱:nexmo-python,代碼行數:8,代碼來源:_internal.py


注:本文中的requests.sessions.Session方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。