Skip to content

Commit

Permalink
♻️ Slight changes to get_client and to_internal_data
Browse files Browse the repository at this point in the history
* add option to raise exceptions for get_client
* no longer make assertions on the response of to_internal_data, because it could be a 204 (empty) response
  • Loading branch information
stevenbal committed Nov 28, 2024
1 parent e5a5ed7 commit 78a8324
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions vng_api_common/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
"""

import logging
from typing import Any, Optional

from django.conf import settings
from django.utils.module_loading import import_string

from ape_pie import APIClient
from requests import JSONDecodeError, RequestException, Response
Expand All @@ -18,6 +14,10 @@ class ClientError(RuntimeError):
pass


class NoServiceConfigured(RuntimeError):
pass


# TODO: use more approriate method name
def to_internal_data(response: Response) -> dict | list | None:
try:
Expand All @@ -33,7 +33,6 @@ def to_internal_data(response: Response) -> dict | list | None:
raise
raise ClientError(response_json if response_json is not None else {}) from exc

assert response_json
return response_json


Expand All @@ -56,18 +55,22 @@ def request(
return super().request(method, url, *args, **kwargs)


def get_client(url: str) -> Client | None:
def get_client(
url: str, raise_exceptions: bool = False, **client_kwargs
) -> Client | None:
"""
Get a client instance for the given URL.
If no suitable client is found, ``None`` is returned.
"""
from zgw_consumers.client import build_client
from zgw_consumers.models import Service

service: Optional[Service] = Service.get_service(url)
service: Service | None = Service.get_service(url)

if not service:
logger.warning(f"No service configured for {url}")
return None
if raise_exceptions:
raise NoServiceConfigured(f"{url} API should be added to Service model")
return

return build_client(service, client_factory=Client)
return build_client(service, client_factory=Client, **client_kwargs)

0 comments on commit 78a8324

Please sign in to comment.