How to use the httpx.dispatch.base.Dispatcher function in httpx

To help you get started, weā€™ve selected a few httpx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / httpx / tests / test_multipart.py View on Github external
import binascii
import cgi
import io
import os
from unittest import mock

import pytest

import httpx
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.content_streams import encode
from httpx.dispatch.base import Dispatcher
from httpx.utils import format_form_param


class MockDispatch(Dispatcher):
    async def send(
        self,
        request: httpx.Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> httpx.Response:
        content = b"".join([part async for part in request.stream])
        return httpx.Response(200, content=content, request=request)


@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))
@pytest.mark.asyncio
async def test_multipart(value, output):
    client = httpx.Client(dispatch=MockDispatch())
github encode / httpx / tests / client / test_cookies.py View on Github external
import json
from http.cookiejar import Cookie, CookieJar

import pytest

from httpx import Client, Cookies, Request, Response
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.dispatch.base import Dispatcher


class MockDispatch(Dispatcher):
    async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        if request.url.path.startswith("/echo_cookies"):
            body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()
            return Response(200, content=body, request=request)
        elif request.url.path.startswith("/set_cookie"):
            headers = {"set-cookie": "example-name=example-value"}
            return Response(200, headers=headers, request=request)
        else:
            raise NotImplementedError  # pragma: no cover
github encode / httpx / tests / client / test_auth.py View on Github external
import hashlib
import json
import os
import typing

import pytest

from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.dispatch.base import Dispatcher


class MockDispatch(Dispatcher):
    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:
        self.auth_header = auth_header
        self.status_code = status_code

    async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        headers = [("www-authenticate", self.auth_header)] if self.auth_header else []
        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()
        return Response(
            self.status_code, headers=headers, content=body, request=request
        )
github encode / httpx / tests / client / test_redirects.py View on Github external
from httpx import (
    URL,
    Client,
    NotRedirectResponse,
    RedirectBodyUnavailable,
    RedirectLoop,
    Request,
    Response,
    TooManyRedirects,
    codes,
)
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.dispatch.base import Dispatcher


class MockDispatch(Dispatcher):
    async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        if request.url.path == "/no_redirect":
            return Response(codes.OK, request=request)

        elif request.url.path == "/redirect_301":
            status_code = codes.MOVED_PERMANENTLY
            headers = {"location": "https://example.org/"}
            return Response(status_code, headers=headers, request=request)

        elif request.url.path == "/redirect_302":
github encode / httpx / tests / client / test_redirects.py View on Github external
async def streaming_body():
        yield b"Example request body"

    with pytest.raises(RedirectBodyUnavailable):
        await client.post(url, data=streaming_body())


@pytest.mark.usefixtures("async_environment")
async def test_cross_subdomain_redirect():
    client = Client(dispatch=MockDispatch())
    url = "https://example.com/cross_subdomain"
    response = await client.get(url)
    assert response.url == URL("https://www.example.org/cross_subdomain")


class MockCookieDispatch(Dispatcher):
    async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        if request.url.path == "/":
            if "cookie" in request.headers:
                content = b"Logged in"
            else:
                content = b"Not logged in"
            return Response(codes.OK, content=content, request=request)

        elif request.url.path == "/login":
            status_code = codes.SEE_OTHER
github encode / httpx / tests / client / test_headers.py View on Github external
#!/usr/bin/env python3

import json

import pytest

from httpx import Client, Headers, Request, Response, __version__
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.dispatch.base import Dispatcher


class MockDispatch(Dispatcher):
    async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        if request.url.path.startswith("/echo_headers"):
            request_headers = dict(request.headers.items())
            body = json.dumps({"headers": request_headers}).encode()
            return Response(200, content=body, request=request)


@pytest.mark.asyncio
async def test_client_header():
    """
github encode / httpx / httpx / dispatch / connection_pool.py View on Github external
del self.by_origin[connection.origin][connection]
        if not self.by_origin[connection.origin]:
            del self.by_origin[connection.origin]

    def clear(self) -> None:
        self.all.clear()
        self.by_origin.clear()

    def __iter__(self) -> typing.Iterator[HTTPConnection]:
        return iter(self.all.keys())

    def __len__(self) -> int:
        return len(self.all)


class ConnectionPool(Dispatcher):
    KEEP_ALIVE_EXPIRY = 5.0

    def __init__(
        self,
        *,
        verify: VerifyTypes = True,
        cert: CertTypes = None,
        trust_env: bool = None,
        pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,
        http2: bool = False,
        backend: typing.Union[str, ConcurrencyBackend] = "auto",
        uds: typing.Optional[str] = None,
    ):
        self.verify = verify
        self.cert = cert
        self.pool_limits = pool_limits
github encode / httpx / httpx / client.py View on Github external
return HTTPProxy(
                url,
                verify=verify,
                cert=cert,
                pool_limits=pool_limits,
                backend=backend,
                trust_env=trust_env,
                http2=http2,
            )
        raise ValueError(f"Unknown proxy for {url!r}")

    if proxies is None:
        return {}
    elif isinstance(proxies, (str, URL)):
        return {"all": _proxy_from_url(proxies)}
    elif isinstance(proxies, Dispatcher):
        return {"all": proxies}
    else:
        new_proxies = {}
        for key, dispatcher_or_url in proxies.items():
            if isinstance(dispatcher_or_url, (str, URL)):
                new_proxies[str(key)] = _proxy_from_url(dispatcher_or_url)
            else:
                new_proxies[str(key)] = dispatcher_or_url
        return new_proxies
github encode / httpx / httpx / dispatch / connection.py View on Github external
from ..backends.base import BaseSocketStream, ConcurrencyBackend, lookup_backend
from ..config import CertTypes, SSLConfig, Timeout, VerifyTypes
from ..models import URL, Origin, Request, Response
from ..utils import get_logger
from .base import Dispatcher, OpenConnection
from .http2 import HTTP2Connection
from .http11 import HTTP11Connection

# Callback signature: async def callback(conn: HTTPConnection) -> None
ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]


logger = get_logger(__name__)


class HTTPConnection(Dispatcher):
    def __init__(
        self,
        origin: typing.Union[str, Origin],
        verify: VerifyTypes = True,
        cert: CertTypes = None,
        trust_env: bool = None,
        http2: bool = False,
        backend: typing.Union[str, ConcurrencyBackend] = "auto",
        release_func: typing.Optional[ReleaseCallback] = None,
        uds: typing.Optional[str] = None,
    ):
        self.origin = Origin(origin) if isinstance(origin, str) else origin
        self.ssl = SSLConfig(cert=cert, verify=verify, trust_env=trust_env)
        self.http2 = http2
        self.backend = lookup_backend(backend)
        self.release_func = release_func