Source code for vmware.vapi.protocol.client.rpc.requests_provider

"""
RPC Provider using Requests Library
"""

__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright (c) 2015 VMware, Inc.  All rights reserved.'


import logging
import requests

from vmware.vapi.protocol.client.rpc.provider import RpcProvider

logger = logging.getLogger(__name__)


[docs]class RequestsRpcProvider(RpcProvider): """ vAPI RPC provider using requests library """ def __init__(self, session, url, timeout, pool_size): """ Initialize RequestsRpcProvider :type session: :class:`requests.Session` :param session: Session object :type msg_protocol: :class:`str` :param msg_protocol: Message protocol to be used for the connection. Valid values are 'json'. :type url: :class:`str` :param url: HTTP(S) URL to be used :type timeout: :class:`int` :param timeout: Request timeout :type pool_size: :class:`int` :param pool_size: Connection pool size to be used """ RpcProvider.__init__(self) self._session = session self._url = url self._pool_size = pool_size self._timeout = timeout def __del__(self): """ Requests rpc provider on delete """ self.disconnect()
[docs] def connect(self): """ connect :rtype: :class:`vmware.vapi.protocol.client.rpc.provider.RpcProvider` :return: http rpc provider """ adapter = requests.adapters.HTTPAdapter( pool_connections=self._pool_size, pool_maxsize=self._pool_size) self._session.mount('http://', adapter) return self
[docs] def disconnect(self): """ disconnect """ pass
[docs] def do_request(self, request_ctx, request): """ Do rpc request :type request_ctx: :class:`dict` of :class:`str`, :class:`str` :param request_ctx: Request context dictionary. The valid key/value pairs are: content-type, {as in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 14.17} :type request: :class:`str` :param request: The request body :rtype: :class:`tuple` of (:class:`dict` of :class:`str`, :class:`str`), :class:`str` :return: Tuple of (response_ctx, response_body) where response_ctx: Response context dictionary. The valid key/value pairs are: content-type, {as in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 14.17} response: The response body """ headers = request_ctx headers['Content-length'] = '%d' % len(request) output = self._session.post(url=self._url, data=request, headers=headers, timeout=self._timeout) # Raise an error if status is 4XX or 5XX output.raise_for_status() response_ctx, response = {}, None if output.status_code == requests.codes.ok: # pylint: disable=E1101 response = output.content content_type = output.headers.get('content-type') if content_type: response_ctx['Content-Type'] = content_type return response_ctx, response