当前位置: 首页>>代码示例>>Python>>正文


Python Session.mount方法代码示例

本文整理汇总了Python中requests.sessions.Session.mount方法的典型用法代码示例。如果您正苦于以下问题:Python Session.mount方法的具体用法?Python Session.mount怎么用?Python Session.mount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.sessions.Session的用法示例。


在下文中一共展示了Session.mount方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: configure_http_session

# 需要导入模块: from requests.sessions import Session [as 别名]
# 或者: from requests.sessions.Session import mount [as 别名]
def configure_http_session(size=20, max_retries=1, _session=None):
    """
    Return a :class:`requests.Session` object configured with
    a :class:`requests.adapters.HTTPAdapter` (connection pool)
    for http and https connections.

    :param size: The connection pool and maximum size.
    :type size: int

    :param max_retries: The maximum number of retries for each connection.
    :type max_retries: int

    :param _session: Test-only hook to provide a pre-configured session.
    """
    if _session is not None:
        return _session

    adapter = HTTPAdapter(
        pool_connections=size,
        pool_maxsize=size,
        max_retries=max_retries,
    )
    session = Session()
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    session.max_redirects = 1
    session.verify = certifi.where()
    return session
开发者ID:amjadm61,项目名称:ichnaea,代码行数:30,代码来源:http.py

示例2: PortalConnection

# 需要导入模块: from requests.sessions import Session [as 别名]
# 或者: from requests.sessions.Session import mount [as 别名]
class PortalConnection(object):
    """
    Connection to HubSpot

    :param authentication_key: This can be either an :class:`APIKey` or an \
            :class:`OAuthKey` instance
    :param basestring change_source: The string passed to HubSpot as \
            ``auditId`` in the query string
    """
    _API_URL = 'https://api.hubapi.com'

    def __init__(self, authentication_key, change_source):
        super(PortalConnection, self).__init__()

        self._authentication_handler = \
            _QueryStringAuthenticationHandler(authentication_key)
        self._change_source = change_source

        self._session = Session()
        self._session.headers['User-Agent'] = _USER_AGENT

        http_adapter = HTTPAdapter(max_retries=_HTTP_CONNECTION_MAX_RETRIES)
        self._session.mount('', http_adapter)

    def send_get_request(self, url_path, query_string_args=None):
        """
        Send a GET request to HubSpot

        :param basestring url_path: The URL path to the endpoint
        :param dict query_string_args: The query string arguments

        :return: Decoded version of the ``JSON`` that HubSpot put in \
                the body of the response.

        """
        return self._send_request('GET', url_path, query_string_args)

    def send_post_request(self, url_path, body_deserialization):
        """
        Send a POST request to HubSpot

        :param basestring url_path: The URL path to the endpoint
        :param dict body_deserialization: The request's body message \
            deserialized

        :return: Decoded version of the ``JSON`` that HubSpot put in \
                the body of the response.
        """
        return self._send_request(
            'POST',
            url_path,
            body_deserialization=body_deserialization,
            )

    def send_put_request(self, url_path, body_deserialization):
        """
        Send a PUT request to HubSpot

        :param basestring url_path: The URL path to the endpoint
        :param body_deserialization: The request's body message deserialized

        :return: Decoded version of the ``JSON`` that HubSpot put in \
                the body of the response.
        """
        return self._send_request(
            'PUT',
            url_path,
            body_deserialization=body_deserialization,
            )

    def send_delete_request(self, url_path):
        """
        Send a DELETE request to HubSpot

        :param basestring url_path: The URL path to the endpoint

        :return: Decoded version of the ``JSON`` that HubSpot put in \
                the body of the response.
        """
        return self._send_request('DELETE', url_path)

    def _send_request(
        self,
        method,
        url_path,
        query_string_args=None,
        body_deserialization=None,
        ):
        url = self._API_URL + url_path

        query_string_args = query_string_args or {}
        query_string_args = dict(query_string_args, auditId=self._change_source)

        request_headers = \
            {'content-type': 'application/json'} if body_deserialization else {}

        if body_deserialization:
            request_body_serialization = json_serialize(body_deserialization)
        else:
            request_body_serialization = None
#.........这里部分代码省略.........
开发者ID:iantaylor,项目名称:hubspot-connection,代码行数:103,代码来源:__init__.py

示例3: __init__

# 需要导入模块: from requests.sessions import Session [as 别名]
# 或者: from requests.sessions.Session import mount [as 别名]
class Connection:

    _API_URL = 'https://www.2degreesnetwork.com/api'

    def __init__(self, auth, timeout=None, api_url=None):
        super(Connection, self).__init__()

        self._api_url = api_url or self._API_URL

        self._authentication_handler = auth

        self._session = Session()
        self._session.headers['User-Agent'] = _USER_AGENT

        self._timeout = timeout

        http_adapter = HTTPAdapter(max_retries=_HTTP_CONNECTION_MAX_RETRIES)
        self._session.mount('', http_adapter)

    def send_get_request(self, url, query_string_args=None):
        """
        Send a GET request

        :param str url: The URL or URL path to the endpoint
        :param dict query_string_args: The query string arguments

        :return: Decoded version of the ``JSON`` the remote put in \
                the body of the response.

        """
        return self._send_request('GET', url, query_string_args)

    def send_head_request(self, url, query_string_args=None):
        """
        Send a HEAD request

        :param str url: The URL or URL path to the endpoint
        :param dict query_string_args: The query string arguments

        """
        return self._send_request('HEAD', url, query_string_args)

    def send_post_request(self, url, body_deserialization=None):
        """
        Send a POST request

        :param str url: The URL or URL path to the endpoint
        :param dict body_deserialization: The request's body message \
            deserialized

        :return: Decoded version of the ``JSON`` the remote put in \
                the body of the response.
        """
        return self._send_request(
            'POST',
            url,
            body_deserialization=body_deserialization,
            )

    def send_put_request(self, url, body_deserialization):
        """
        Send a PUT request

        :param str url: The URL or URL path to the endpoint
        :param body_deserialization: The request's body message deserialized

        :return: Decoded version of the ``JSON`` the remote put in \
                the body of the response.
        """
        return self._send_request(
            'PUT',
            url,
            body_deserialization=body_deserialization,
            )

    def send_delete_request(self, url):
        """
        Send a DELETE request

        :param str url: The URL or URL path to the endpoint

        :return: Decoded version of the ``JSON`` the remote put in \
                the body of the response.
        """
        return self._send_request('DELETE', url)

    def _send_request(
        self,
        method,
        url,
        query_string_args=None,
        body_deserialization=None,
        ):
        if url.startswith(self._api_url):
            url = url
        else:
            url = self._api_url + url

        query_string_args = query_string_args or {}

#.........这里部分代码省略.........
开发者ID:2degrees,项目名称:twapi-connection,代码行数:103,代码来源:__init__.py

示例4: MWS

# 需要导入模块: from requests.sessions import Session [as 别名]
# 或者: from requests.sessions.Session import mount [as 别名]
class MWS(object):
    """ Base Amazon API class """

    # This is used to post/get to the different uris used by amazon per api
    # ie. /Orders/2011-01-01
    # All subclasses must define their own URI only if needed
    URI = "/"

    # The API version varies in most amazon APIs
    VERSION = "2009-01-01"

    # There seem to be some xml namespace issues. therefore every api subclass
    # is recommended to define its namespace, so that it can be referenced
    # like so AmazonAPISubclass.NS.
    # For more information see http://stackoverflow.com/a/8719461/389453
    NS = ''

    # Some APIs are available only to either a "Merchant" or "Seller"
    # the type of account needs to be sent in every call to the amazon MWS.
    # This constant defines the exact name of the parameter Amazon expects
    # for the specific API being used.
    # All subclasses need to define this if they require another account type
    # like "Merchant" in which case you define it like so.
    # ACCOUNT_TYPE = "Merchant"
    # Which is the name of the parameter for that specific account type.
    ACCOUNT_TYPE = "SellerId"

    def __init__(self, access_key, secret_key, account_id,
                 domain='https://mws.amazonservices.com', uri="", version=""):
        self.access_key = access_key
        self.secret_key = secret_key
        self.account_id = account_id
        self.domain = domain
        self.uri = uri or self.URI
        self.version = version or self.VERSION
        self.session = Session()

        bucket_key = getattr(settings, 'RUNSCOPE_BUCKET_KEY', None)
        if bucket_key:
            logger.info("Redirecting API calls for MWS to runscope")
            self.configure_runscope(bucket_key)

    def configure_runscope(self, bucket_key):
        """
        Configure all connections to be proxied through runscope for easier
        debugging and logging of all requests and responses. *bucket_key* is
        API for the bucket you want to use for all the request. Check Runscope
        for more details on that.
        """
        try:
            from requests_runscope import RunscopeAdapter
        except ImportError:
            logger.error(
                "Could not import runscope adapter. Is requests-runscope "
                "installed? Try running pip install requests-runscope."
            )
        else:
            logger.info(
                'Mounting runscope proxy adapter for bucket {}'.format(
                    bucket_key
                )
            )
            self.session.mount('https://', RunscopeAdapter(bucket_key))
            self.session.mount('http://', RunscopeAdapter(bucket_key))

    def _get_quote_params(self, params):
        quoted_params = []
        for key in sorted(params):
            value = urllib.quote(
                unicode(params[key]).encode('utf-8'),
                safe='-_.~'
            )
            quoted_params.append("{}={}".format(key, value))
        return '&'.join(quoted_params)

    def make_request(self, extra_data, method="GET", **kwargs):
        """
        Make request to Amazon MWS API with these parameters
        """

        # Remove all keys with an empty value because
        # Amazon's MWS does not allow such a thing.
        extra_data = remove_empty(extra_data)
        params = {
            'AWSAccessKeyId': self.access_key,
            self.ACCOUNT_TYPE: self.account_id,
            'SignatureVersion': '2',
            'Timestamp': self.get_timestamp(),
            'Version': self.version,
            'SignatureMethod': 'HmacSHA256',
        }
        params.update(extra_data)
        logger.debug("Request Parameters: {}".format(params))

        request_description = self._get_quote_params(params)
        signature = self.calc_signature(method, request_description)

        logger.debug('Domain: {} URI: {}'.format(self.domain, self.uri))
        url = '%s%s?%s&Signature=%s' % (self.domain, self.uri,
                                        request_description,
#.........这里部分代码省略.........
开发者ID:ButchershopCreative,项目名称:django-oscar-mws,代码行数:103,代码来源:api.py

示例5: DebugSession

# 需要导入模块: from requests.sessions import Session [as 别名]
# 或者: from requests.sessions.Session import mount [as 别名]
def DebugSession(session=None):
    if session is None:
        session = Session()
    session.mount('https://', DebugAdapter())
    session.mount('http://', DebugAdapter())
    return session
开发者ID:core-api,项目名称:coreapi-cli,代码行数:8,代码来源:debug.py


注:本文中的requests.sessions.Session.mount方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。