Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 6 additions & 24 deletions lago_python_client/base_client.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from abc import ABC, abstractmethod
from typing import Optional, Type
from abc import ABC
from typing import Any, ClassVar, Optional, Type

from lago_python_client.base_model import BaseModel
from lago_python_client.services.rate_limit import RateLimitRetryConfig


class BaseClient(ABC):
"""The base class used for each collection client."""

API_RESOURCE: ClassVar[str]
RESPONSE_MODEL: ClassVar[Type[Any]]
ROOT_NAME: ClassVar[str]

def __init__(
self,
base_url: str,
Expand All @@ -19,24 +22,3 @@ def __init__(
self.api_key = api_key
self.base_ingest_url = base_ingest_url
self.rate_limit_retry_config = rate_limit_retry_config or RateLimitRetryConfig()

@property
@classmethod
@abstractmethod
def API_RESOURCE(cls) -> str:
"""Collection name (required class property) used to build query urls."""
raise NotImplementedError

@property
@classmethod
@abstractmethod
def RESPONSE_MODEL(cls) -> Type[BaseModel]:
"""Response model (required class property) used to prepare response."""
raise NotImplementedError

@property
@classmethod
@abstractmethod
def ROOT_NAME(cls) -> str:
"""The resource key (required class property), used to access the response data."""
raise NotImplementedError
85 changes: 45 additions & 40 deletions lago_python_client/mixins.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import warnings
from typing import Any, Generic, Optional, Type, TypeVar, Union
from typing import Any, Callable, ClassVar, Generic, Optional, Tuple, Type, TypeVar, Union, cast

import httpx

Expand Down Expand Up @@ -37,20 +37,20 @@


class _ClientMixin(Protocol[_PM_co]):
@property
def PARENT_API_RESOURCE(self) -> str: ...
@property
def API_RESOURCE(self) -> str: ...
@property
def RESPONSE_MODEL(self) -> Type[_PM_co]: ...
@property
def ROOT_NAME(self) -> str: ...
@property
def api_key(self) -> str: ...
@property
def base_url(self) -> str: ...
@property
def rate_limit_retry_config(self) -> RateLimitRetryConfig: ...
API_RESOURCE: ClassVar[str]
RESPONSE_MODEL: ClassVar[Type[Any]]
ROOT_NAME: ClassVar[str]
api_key: str
base_url: str
rate_limit_retry_config: RateLimitRetryConfig


class _ChildClientMixin(_ClientMixin[_PM_co], Protocol[_PM_co]):
PARENT_API_RESOURCE: ClassVar[str]


class _NestedClientMixin(_ClientMixin[_PM_co], Protocol[_PM_co]):
api_resource: Callable[..., Tuple[str, ...]]


class CreateCommandMixin(Generic[_M]):
Expand Down Expand Up @@ -95,7 +95,7 @@ class DestroyCommandMixin(Generic[_M]):
def destroy(
self: _ClientMixin[_M],
resource_id: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = DEFAULT_TIMEOUT,
) -> BaseModel:
"""Execute `destroy` command."""
Expand Down Expand Up @@ -125,7 +125,7 @@ class FindAllCommandMixin(Generic[_M]):

def find_all(
self: _ClientMixin[_M],
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = DEFAULT_TIMEOUT,
) -> Mapping[str, Any]:
"""Execute `find all` command."""
Expand Down Expand Up @@ -155,9 +155,9 @@ class FindAllChildrenCommandMixin(Generic[_M]):
"""Client mixin with `find_all` command scoped to a parent resource."""

def find_all(
self: _ClientMixin[_M],
self: _ChildClientMixin[_M],
resource_id: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = DEFAULT_TIMEOUT,
*,
timetour: Optional[httpx.Timeout] = None,
Expand Down Expand Up @@ -195,10 +195,10 @@ class FindChildCommandMixin(Generic[_M]):
"""Client mixin with `find` command scoped to a parent resource."""

def find(
self: _ClientMixin[_M],
self: _ChildClientMixin[_M],
parent_id: str,
child_id: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
) -> _M:
"""Execute `find` child command."""
if options is None:
Expand Down Expand Up @@ -228,10 +228,10 @@ class CreateChildCommandMixin(Generic[_M]):
"""Client mixin with `create` command scoped to a parent resource."""

def create(
self: _ClientMixin[_M],
self: _ChildClientMixin[_M],
parent_id: str,
input_object: BaseModel,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
) -> _M:
"""Execute `create` child command."""
if options is None:
Expand Down Expand Up @@ -261,11 +261,11 @@ class UpdateChildCommandMixin(Generic[_M]):
"""Client mixin with `update` command scoped to a parent resource."""

def update(
self: _ClientMixin[_M],
self: _ChildClientMixin[_M],
parent_id: str,
child_id: str,
input_object: BaseModel,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
) -> _M:
"""Execute `update` child command."""
if options is None:
Expand Down Expand Up @@ -296,10 +296,10 @@ class DestroyChildCommandMixin(Generic[_M]):
"""Client mixin with `destroy` command scoped to a parent resource."""

def destroy(
self: _ClientMixin[_M],
self: _ChildClientMixin[_M],
parent_id: str,
child_id: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
) -> _M:
"""Execute `destroy` child command."""
if options is None:
Expand Down Expand Up @@ -331,7 +331,7 @@ class FindCommandMixin(Generic[_M]):
def find(
self: _ClientMixin[_M],
resource_id: str,
params: QueryPairs = None,
params: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = DEFAULT_TIMEOUT,
) -> _M:
"""Execute `find` command."""
Expand Down Expand Up @@ -393,13 +393,15 @@ class NestedCreateCommandMixin(Generic[_M]):
"""Client mixin with `create` command."""

def create(
self: _ClientMixin[_M],
self: _NestedClientMixin[_M],
*args: Union[str, BaseModel],
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = None,
) -> Optional[_M]:
"""Execute `create` command."""
*parent_ids, input_object = args
*raw_parent_ids, raw_input_object = args
parent_ids = cast(Tuple[str, ...], tuple(raw_parent_ids))
input_object = cast(BaseModel, raw_input_object)

# Send request and save response
api_response: Response = send_post_request(
Expand Down Expand Up @@ -429,13 +431,16 @@ class NestedUpdateCommandMixin(Generic[_M]):
"""Client mixin with `update` command."""

def update(
self: _ClientMixin[_M],
self: _NestedClientMixin[_M],
*args: Union[str, BaseModel],
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = None,
) -> _M:
"""Execute `update` command."""
*parent_ids, resource_id, input_object = args
*raw_parent_ids, raw_resource_id, raw_input_object = args
parent_ids = cast(Tuple[str, ...], tuple(raw_parent_ids))
resource_id = cast(str, raw_resource_id)
input_object = cast(BaseModel, raw_input_object)

# Send request and save response
api_response: Response = send_put_request(
Expand Down Expand Up @@ -465,9 +470,9 @@ class NestedDestroyCommandMixin(Generic[_M]):
"""Client mixin with `destroy` command."""

def destroy(
self: _ClientMixin[_M],
self: _NestedClientMixin[_M],
*args: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = None,
) -> BaseModel:
"""Execute `destroy` command."""
Expand Down Expand Up @@ -496,9 +501,9 @@ class NestedFindCommandMixin(Generic[_M]):
"""Client mixin with `find` command."""

def find(
self: _ClientMixin[_M],
self: _NestedClientMixin[_M],
*args: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = None,
) -> _M:
"""Execute `find` command."""
Expand Down Expand Up @@ -527,9 +532,9 @@ class NestedFindAllCommandMixin(Generic[_M]):
"""Client mixin with `find_all` command."""

def find_all(
self: _ClientMixin[_M],
self: _NestedClientMixin[_M],
*parent_ids: str,
options: QueryPairs = None,
options: Optional[QueryPairs] = None,
timeout: Optional[httpx.Timeout] = None,
) -> Mapping[str, Any]:
"""Execute `find all` command."""
Expand Down
2 changes: 1 addition & 1 deletion lago_python_client/services/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def make_url(
*,
origin: str,
path_parts: Sequence[str],
query_pairs: QueryPairs = None,
query_pairs: Optional[QueryPairs] = None,
) -> str:
"""Return a URL, treating each path part as an unencoded segment."""
if query_pairs is None:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_mixin_protocols.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import Tuple, Type

from lago_python_client.client import Client
from lago_python_client.customers.applied_coupons_client import CustomerAppliedCouponsClient
from lago_python_client.mixins import _ChildClientMixin, _ClientMixin, _NestedClientMixin
from lago_python_client.models.applied_coupon import AppliedCouponResponse
from lago_python_client.models.subscription import SubscriptionResponse
from lago_python_client.subscriptions.alert_client import SubscriptionAlertClient
from lago_python_client.subscriptions.charges_client import SubscriptionChargesClient
from lago_python_client.subscriptions.clients import SubscriptionClient


def accept_client_mixin(client: _ClientMixin[SubscriptionResponse]) -> Type[SubscriptionResponse]:
return client.RESPONSE_MODEL


def accept_child_client_mixin(client: _ChildClientMixin[AppliedCouponResponse]) -> str:
return client.PARENT_API_RESOURCE


def accept_nested_client_mixin(client: _NestedClientMixin) -> Tuple[str, ...]:
return client.api_resource("sub_1")


def test_client_mixin_protocols_and_classvars():
client = Client(api_key="test-key")
sub_client = SubscriptionClient(client.base_api_url, client.api_key)
charges_client = SubscriptionChargesClient(client.base_api_url, client.api_key)
applied_coupons_client = CustomerAppliedCouponsClient(client.base_api_url, client.api_key)
alert_client = SubscriptionAlertClient(client.base_api_url, client.api_key)

assert accept_client_mixin(sub_client) is SubscriptionResponse
assert accept_child_client_mixin(applied_coupons_client) == "customers"
assert accept_nested_client_mixin(alert_client) == ("subscriptions", "sub_1", "alerts")
assert charges_client.PARENT_API_RESOURCE == "subscriptions"
assert sub_client.API_RESOURCE == "subscriptions"