Skip to content
Merged
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
665 changes: 0 additions & 665 deletions mpt_api_client/http/mixins.py

This file was deleted.

63 changes: 63 additions & 0 deletions mpt_api_client/http/mixins/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from mpt_api_client.http.mixins.collection_mixin import (
AsyncCollectionMixin,
CollectionMixin,
)
from mpt_api_client.http.mixins.create_file_mixin import (
AsyncCreateFileMixin,
CreateFileMixin,
)
from mpt_api_client.http.mixins.create_mixin import AsyncCreateMixin, CreateMixin
from mpt_api_client.http.mixins.delete_mixin import AsyncDeleteMixin, DeleteMixin
from mpt_api_client.http.mixins.disable_mixin import AsyncDisableMixin, DisableMixin
from mpt_api_client.http.mixins.download_file_mixin import (
AsyncDownloadFileMixin,
DownloadFileMixin,
)
from mpt_api_client.http.mixins.enable_mixin import AsyncEnableMixin, EnableMixin
from mpt_api_client.http.mixins.file_operations_mixin import (
AsyncFilesOperationsMixin,
FilesOperationsMixin,
)
from mpt_api_client.http.mixins.get_mixin import AsyncGetMixin, GetMixin
from mpt_api_client.http.mixins.queryable_mixin import QueryableMixin
from mpt_api_client.http.mixins.resource_mixins import (
AsyncManagedResourceMixin,
AsyncModifiableResourceMixin,
ManagedResourceMixin,
ModifiableResourceMixin,
)
from mpt_api_client.http.mixins.update_file_mixin import (
AsyncUpdateFileMixin,
UpdateFileMixin,
)
from mpt_api_client.http.mixins.update_mixin import AsyncUpdateMixin, UpdateMixin

__all__ = [ # noqa: WPS410
"AsyncCollectionMixin",
"AsyncCreateFileMixin",
"AsyncCreateMixin",
"AsyncDeleteMixin",
"AsyncDisableMixin",
"AsyncDownloadFileMixin",
"AsyncEnableMixin",
"AsyncFilesOperationsMixin",
"AsyncGetMixin",
"AsyncManagedResourceMixin",
"AsyncModifiableResourceMixin",
"AsyncUpdateFileMixin",
"AsyncUpdateMixin",
"CollectionMixin",
"CreateFileMixin",
"CreateMixin",
"DeleteMixin",
"DisableMixin",
"DownloadFileMixin",
"EnableMixin",
"FilesOperationsMixin",
"GetMixin",
"ManagedResourceMixin",
"ModifiableResourceMixin",
"QueryableMixin",
"UpdateFileMixin",
"UpdateMixin",
]
145 changes: 145 additions & 0 deletions mpt_api_client/http/mixins/collection_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
from collections.abc import AsyncIterator, Iterator

from mpt_api_client.http.mixins.queryable_mixin import QueryableMixin
from mpt_api_client.http.types import Response
from mpt_api_client.models import Collection
from mpt_api_client.models import Model as BaseModel


class CollectionMixin[Model: BaseModel](QueryableMixin):
"""Mixin providing collection functionality."""

def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[Model]:
"""Fetch one page of resources.

Returns:
Collection of resources.
"""
response = self._fetch_page_as_response(limit=limit, offset=offset)
return self.make_collection(response) # type: ignore[attr-defined, no-any-return]

def fetch_one(self) -> Model:
"""Fetch one resource, expect exactly one result.

Returns:
One resource.

Raises:
ValueError: If the total matching records are not exactly one.
"""
response = self._fetch_page_as_response(limit=1, offset=0)
resource_list = self.make_collection(response) # type: ignore[attr-defined]
total_records = len(resource_list)
if resource_list.meta:
total_records = resource_list.meta.pagination.total
if total_records == 0:
raise ValueError("Expected one result, but got zero results")
if total_records > 1:
raise ValueError(f"Expected one result, but got {total_records} results")

return resource_list[0] # type: ignore[no-any-return]

def iterate(self, batch_size: int = 100) -> Iterator[Model]:
"""Iterate over all resources, yielding GenericResource objects.

Args:
batch_size: Number of resources to fetch per request

Returns:
Iterator of resources.
"""
offset = 0
limit = batch_size # Default page size

while True:
response = self._fetch_page_as_response(limit=limit, offset=offset)
items_collection = self.make_collection(response) # type: ignore[attr-defined]
yield from items_collection

if not items_collection.meta:
break
if not items_collection.meta.pagination.has_next():
break
offset = items_collection.meta.pagination.next_offset()

def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> Response:
"""Fetch one page of resources.

Returns:
Response object.

Raises:
HTTPStatusError: if the response status code is not 200.
"""
pagination_params: dict[str, int] = {"limit": limit, "offset": offset}
return self.http_client.request("get", self.build_path(pagination_params)) # type: ignore[attr-defined, no-any-return]


class AsyncCollectionMixin[Model: BaseModel](QueryableMixin):
"""Async mixin providing collection functionality."""

async def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[Model]:
"""Fetch one page of resources.

Returns:
Collection of resources.
"""
response = await self._fetch_page_as_response(limit=limit, offset=offset)
return self.make_collection(response) # type: ignore[no-any-return,attr-defined]

async def fetch_one(self) -> Model:
"""Fetch one resource, expect exactly one result.

Returns:
One resource.

Raises:
ValueError: If the total matching records are not exactly one.
"""
response = await self._fetch_page_as_response(limit=1, offset=0)
resource_list = self.make_collection(response) # type: ignore[attr-defined]
total_records = len(resource_list)
if resource_list.meta:
total_records = resource_list.meta.pagination.total
if total_records == 0:
raise ValueError("Expected one result, but got zero results")
if total_records > 1:
raise ValueError(f"Expected one result, but got {total_records} results")

return resource_list[0] # type: ignore[no-any-return]

async def iterate(self, batch_size: int = 100) -> AsyncIterator[Model]:
"""Iterate over all resources, yielding GenericResource objects.

Args:
batch_size: Number of resources to fetch per request

Returns:
Iterator of resources.
"""
offset = 0
limit = batch_size # Default page size

while True:
response = await self._fetch_page_as_response(limit=limit, offset=offset)
items_collection = self.make_collection(response) # type: ignore[attr-defined]
for resource in items_collection:
yield resource

if not items_collection.meta:
break
if not items_collection.meta.pagination.has_next():
break
offset = items_collection.meta.pagination.next_offset()

async def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> Response:
"""Fetch one page of resources.

Returns:
Response object.

Raises:
HTTPStatusError: if the response status code is not 200.
"""
pagination_params: dict[str, int] = {"limit": limit, "offset": offset}
return await self.http_client.request("get", self.build_path(pagination_params)) # type: ignore[attr-defined,no-any-return]
66 changes: 66 additions & 0 deletions mpt_api_client/http/mixins/create_file_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from mpt_api_client.http.types import FileTypes
from mpt_api_client.models import ResourceData


class CreateFileMixin[Model]:
"""Create file mixin."""

def create(self, resource_data: ResourceData, file: FileTypes | None = None) -> Model: # noqa: WPS110
"""Create logo.

Create a file resource by specifying a file image.

Args:
resource_data: Resource data.
file: File image.

Returns:
Model: Created resource.
"""
files = {}

if file:
files[self._upload_file_key] = file # type: ignore[attr-defined]

response = self.http_client.request( # type: ignore[attr-defined]
"post",
self.path, # type: ignore[attr-defined]
json=resource_data,
files=files,
json_file_key=self._upload_data_key, # type: ignore[attr-defined]
force_multipart=True,
)

return self._model_class.from_response(response) # type: ignore[attr-defined, no-any-return]


class AsyncCreateFileMixin[Model]:
"""Asynchronous Create file mixin."""

async def create(self, resource_data: ResourceData, file: FileTypes | None = None) -> Model: # noqa: WPS110
"""Create file.

Create a file resource by specifying a file.

Args:
resource_data: Resource data.
file: File image.

Returns:
Model: Created resource.
"""
files = {}

if file:
files[self._upload_file_key] = file # type: ignore[attr-defined]

response = await self.http_client.request( # type: ignore[attr-defined]
"post",
self.path, # type: ignore[attr-defined]
json=resource_data,
files=files,
json_file_key=self._upload_data_key, # type: ignore[attr-defined]
force_multipart=True,
)

return self._model_class.from_response(response) # type: ignore[attr-defined, no-any-return]
29 changes: 29 additions & 0 deletions mpt_api_client/http/mixins/create_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from mpt_api_client.models import ResourceData


class CreateMixin[Model]:
"""Create resource mixin."""

def create(self, resource_data: ResourceData) -> Model:
"""Create a new resource using `POST /endpoint`.

Returns:
New resource created.
"""
response = self.http_client.request("post", self.path, json=resource_data) # type: ignore[attr-defined]

return self._model_class.from_response(response) # type: ignore[attr-defined, no-any-return]


class AsyncCreateMixin[Model]:
"""Create resource mixin."""

async def create(self, resource_data: ResourceData) -> Model:
"""Create a new resource using `POST /endpoint`.

Returns:
New resource created.
"""
response = await self.http_client.request("post", self.path, json=resource_data) # type: ignore[attr-defined]

return self._model_class.from_response(response) # type: ignore[attr-defined, no-any-return]
26 changes: 26 additions & 0 deletions mpt_api_client/http/mixins/delete_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from urllib.parse import urljoin


class DeleteMixin:
"""Delete resource mixin."""

def delete(self, resource_id: str) -> None:
"""Delete resource using `DELETE /endpoint/{resource_id}`.

Args:
resource_id: Resource ID.
"""
self._resource_do_request(resource_id, "DELETE") # type: ignore[attr-defined]


class AsyncDeleteMixin:
"""Delete resource mixin."""

async def delete(self, resource_id: str) -> None:
"""Delete resource using `DELETE /endpoint/{resource_id}`.

Args:
resource_id: Resource ID.
"""
url = urljoin(f"{self.path}/", resource_id) # type: ignore[attr-defined]
await self.http_client.request("delete", url) # type: ignore[attr-defined]
22 changes: 22 additions & 0 deletions mpt_api_client/http/mixins/disable_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from mpt_api_client.models import Model as BaseModel
from mpt_api_client.models import ResourceData


class AsyncDisableMixin[Model: BaseModel]:
"""Disable resource mixin."""

async def disable(self, resource_id: str, resource_data: ResourceData | None = None) -> Model:
"""Disable a specific resource."""
return await self._resource_action( # type: ignore[attr-defined, no-any-return]
resource_id=resource_id, method="POST", action="disable", json=resource_data
)


class DisableMixin[Model: BaseModel]:
"""Disable resource mixin."""

def disable(self, resource_id: str, resource_data: ResourceData | None = None) -> Model:
"""Disable a specific resource."""
return self._resource_action( # type: ignore[attr-defined, no-any-return]
resource_id=resource_id, method="POST", action="disable", json=resource_data
)
Loading