bibajz / bitcoin-python-async-rpc

Minimal Bitcoin JSON-RPC Python asynchronous client
MIT License
33 stars 12 forks source link

Customization of `httpx.AsyncClient` during `BitcoinRPC` initialization #4

Closed bibajz closed 3 years ago

bibajz commented 4 years ago

As noted in #3, httpx.AsyncClient basic settings are fine in most cases.

However, if one needs to a more fine-grained customization due to need of more concurrent connections, proxies, etc., they have no option to do so now.

For now, I have a following solution in mind:

class ImproperlyConfigured(Exception):
    pass

class BitcoinRPC:
    def __init__(self, host: str, port: int, rpc_user: str, rpc_password: str, **kwargs) -> None:
        self._url = self._set_url(host, port)
        self._client = self._configure_client(rpc_user, rpc_password, **kwargs)

    @staticmethod
    def _configure_client(rpc_user: str, rpc_password: str, **options) -> httpx.AsyncClient:
        auth = (rpc_user, rpc_password)
        headers = {"content-type": "application/json"}

        options = dict(options)
        if not options:
            return httpx.AsyncClient(auth=auth, headers=headers)

        if "auth" in options:
            raise ImproperlyConfigured("Authentication cannot be set via options!")

        if "headers" in options:
            _additional_headers = dict(options.pop("headers")) 
            headers.update(_additional_headers)
            # guard against content-type overwrite
            headers["content-type"] = "application/json"

        return httpx.AsyncClient(auth=auth, headers=headers, **options)

All the keyword arguments passed to the initializer of BitcoinRPC will be passed directly to the httpx.AsyncClient, with the exception of auth keyword. Also, headers will need to be tamed a bit with the content-type key since it is supposed to be application/json.

It will then be this library's user's responsibility to conform to the interface exposed by httpx.AsyncClient's initiliazer.

bibajz commented 3 years ago

Resolved in https://github.com/bibajz/bitcoin-python-async-rpc/commit/0aab77b43efb75be1624940501c2d49650c5ca17