Python requests.auth.AuthBase() Examples

The following are 10 code examples of requests.auth.AuthBase(). 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.auth , or try the search function .
Example #1
Source File: client.py    From rets with MIT License 6 votes vote down vote up
def _get_http_auth(username: str, password: str, auth_type: str) -> AuthBase:
    if auth_type == 'basic':
        return HTTPBasicAuth(username, password)
    if auth_type == 'digest':
        return HTTPDigestAuth(username, password)
    raise RetsClientError('unknown auth type %s' % auth_type) 
Example #2
Source File: connection.py    From openeo-python-client with Apache License 2.0 5 votes vote down vote up
def __init__(self, root_url: str, auth: AuthBase = None, session: requests.Session = None,
                 default_timeout: int = None):
        self._root_url = root_url
        self.auth = auth or NullAuth()
        self.session = session or requests.Session()
        self.default_timeout = default_timeout
        self.default_headers = {
            "User-Agent": "openeo-python-client/{cv} {py}/{pv} {pl}".format(
                cv=openeo.client_version(),
                py=sys.implementation.name, pv=".".join(map(str, sys.version_info[:3])),
                pl=sys.platform
            )
        } 
Example #3
Source File: connection.py    From openeo-python-client with Apache License 2.0 5 votes vote down vote up
def request(self, method: str, path: str, headers: dict = None, auth: AuthBase = None,
                check_error=True, expected_status=None, **kwargs):
        """Generic request send"""
        url = self.build_url(path)
        auth = auth or self.auth
        if _log.isEnabledFor(logging.DEBUG):
            _log.debug("Request `{m} {u}` with headers {h}, auth {a}, kwargs {k}".format(
                m=method.upper(), u=url, h=headers and headers.keys(), a=type(auth).__name__, k=list(kwargs.keys()))
            )
        resp = self.session.request(
            method=method,
            url=url,
            headers=self._merged_headers(headers),
            auth=auth,
            timeout=kwargs.pop("timeout", self.default_timeout),
            **kwargs
        )
        # Check for API errors and unexpected HTTP status codes as desired.
        status = resp.status_code
        if check_error and status >= 400:
            self._raise_api_error(resp)
        if expected_status and status not in ensure_list(expected_status):
            raise OpenEoClientException("Got status code {s!r} for `{m} {p}` (expected {e!r})".format(
                m=method.upper(), p=path, s=status, e=expected_status)
            )
        return resp 
Example #4
Source File: connection.py    From openeo-python-client with Apache License 2.0 5 votes vote down vote up
def get(self, path, stream=False, auth: AuthBase = None, **kwargs) -> Response:
        """
        Do GET request to REST API.

        :param path: API path (without root url)
        :param stream: True if the get request should be streamed, else False
        :param auth: optional custom authentication to use instead of the default one
        :return: response: Response
        """
        return self.request("get", path=path, stream=stream, auth=auth, **kwargs) 
Example #5
Source File: connection.py    From openeo-python-client with Apache License 2.0 5 votes vote down vote up
def __init__(self, url, auth: AuthBase = None, session: requests.Session = None, default_timeout: int = None):
        """
        Constructor of Connection, authenticates user.

        :param url: String Backend root url
        """
        super().__init__(root_url=url, auth=auth, session=session, default_timeout=default_timeout)
        self._cached_capabilities = None

        # Initial API version check.
        if self._api_version.below(self._MINIMUM_API_VERSION):
            raise ApiVersionException("OpenEO API version should be at least {m!s}, but got {v!s}".format(
                m=self._MINIMUM_API_VERSION, v=self._api_version)
            ) 
Example #6
Source File: session.py    From qiskit-ibmq-provider with Apache License 2.0 5 votes vote down vote up
def __init__(
            self,
            base_url: str,
            access_token: Optional[str] = None,
            retries_total: int = 5,
            retries_connect: int = 3,
            backoff_factor: float = 0.5,
            verify: bool = True,
            proxies: Optional[Dict[str, str]] = None,
            auth: Optional[AuthBase] = None,
            timeout: Tuple[float, Union[float, None]] = (5.0, None)
    ) -> None:
        """RetrySession constructor.

        Args:
            base_url: Base URL for the session's requests.
            access_token: Access token.
            retries_total: Number of total retries for the requests.
            retries_connect: Number of connect retries for the requests.
            backoff_factor: Backoff factor between retry attempts.
            verify: Whether to enable SSL verification.
            proxies: Proxy URLs mapped by protocol.
            auth: Authentication handler.
            timeout: Timeout for the requests, in the form of (connection_timeout,
                total_timeout).
        """
        super().__init__()

        self.base_url = base_url
        self._access_token = access_token
        self.access_token = access_token

        self._initialize_retry(retries_total, retries_connect, backoff_factor)
        self._initialize_session_parameters(verify, proxies or {}, auth)
        self._timeout = timeout 
Example #7
Source File: session.py    From qiskit-ibmq-provider with Apache License 2.0 5 votes vote down vote up
def _initialize_session_parameters(
            self,
            verify: bool,
            proxies: Dict[str, str],
            auth: Optional[AuthBase] = None
    ) -> None:
        """Set the session parameters and attributes.

        Args:
            verify: Whether to enable SSL verification.
            proxies: Proxy URLs mapped by protocol.
            auth: Authentication handler.
        """
        client_app_header = CLIENT_APPLICATION

        # Append custom header to the end if specified
        custom_header = os.getenv(CUSTOM_HEADER_ENV_VAR)
        if custom_header:
            client_app_header += "/" + custom_header

        self.headers.update({'X-Qx-Client-Application': client_app_header})
        self.headers['Content-Type'] = 'application/json'

        self.auth = auth
        self.proxies = proxies or {}
        self.verify = verify 
Example #8
Source File: http_request_manager.py    From python-domino with Apache License 2.0 5 votes vote down vote up
def __init__(self, auth: AuthBase):
        self.auth = auth 
Example #9
Source File: test_usage_reporter.py    From fiaas-deploy-daemon with Apache License 2.0 5 votes vote down vote up
def mock_auth(self):
        return mock.create_autospec(AuthBase()) 
Example #10
Source File: requests.py    From gql with MIT License 4 votes vote down vote up
def __init__(
        self,
        url: str,
        headers: Optional[Dict[str, Any]] = None,
        cookies: Optional[Union[Dict[str, Any], RequestsCookieJar]] = None,
        auth: Optional[AuthBase] = None,
        use_json: bool = True,
        timeout: Optional[int] = None,
        verify: bool = True,
        retries: int = 0,
        method: str = "POST",
        **kwargs: Any
    ):
        """Initialize the transport with the given request parameters.

        :param url: The GraphQL server URL.
        :param headers: Dictionary of HTTP Headers to send with the :class:`Request`
            (Default: None).
        :param cookies: Dict or CookieJar object to send with the :class:`Request`
            (Default: None).
        :param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth
            (Default: None).
        :param use_json: Send request body as JSON instead of form-urlencoded
            (Default: True).
        :param timeout: Specifies a default timeout for requests (Default: None).
        :param verify: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. (Default: True).
        :param retries: Pre-setup of the requests' Session for performing retries
        :param method: HTTP method used for requests. (Default: POST).
        :param kwargs: Optional arguments that ``request`` takes.
            These can be seen at the :requests_: source code or the official :docs_:

        .. _requests: https://github.com/psf/requests/blob/master/requests/api.py
        .. _docs: https://requests.readthedocs.io/en/master/
        """
        self.url = url
        self.headers = headers
        self.cookies = cookies
        self.auth = auth
        self.use_json = use_json
        self.default_timeout = timeout
        self.verify = verify
        self.retries = retries
        self.method = method
        self.kwargs = kwargs

        self.session = None