当前位置: 首页>>代码示例>>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;未经允许,请勿转载。