mopux 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mopux/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ """Official Python SDK for the Mopux API."""
2
+
3
+ from ._async.client import AsyncMopux
4
+ from ._async.connector import AsyncConnector
5
+ from ._base import UNSET, Unset
6
+ from ._retry import RetryPolicy
7
+ from ._sync.client import Mopux
8
+ from ._sync.connector import Connector
9
+ from ._version import __version__
10
+ from .errors import (
11
+ ApiError,
12
+ AuthenticationError,
13
+ AuthorizationError,
14
+ ClientError,
15
+ InvalidInputError,
16
+ MalformedResponseError,
17
+ MopuxConnectionError,
18
+ MopuxError,
19
+ NotFoundError,
20
+ RateLimitError,
21
+ ServerError,
22
+ UncertainWriteError,
23
+ ValidationError,
24
+ )
25
+ from .page import Page
26
+ from .upload import Upload
27
+
28
+ TaskStatuses = {"pending": 0, "in_progress": 1, "review": 2, "done": 3}
29
+ TaskPriorities = {"low": 0, "normal": 1, "high": 2, "maximum": 9}
30
+
31
+ __all__ = [
32
+ "UNSET",
33
+ "ApiError",
34
+ "AsyncConnector",
35
+ "AsyncMopux",
36
+ "AuthenticationError",
37
+ "AuthorizationError",
38
+ "ClientError",
39
+ "Connector",
40
+ "InvalidInputError",
41
+ "MalformedResponseError",
42
+ "Mopux",
43
+ "MopuxConnectionError",
44
+ "MopuxError",
45
+ "NotFoundError",
46
+ "Page",
47
+ "RateLimitError",
48
+ "RetryPolicy",
49
+ "ServerError",
50
+ "TaskPriorities",
51
+ "TaskStatuses",
52
+ "UncertainWriteError",
53
+ "Unset",
54
+ "Upload",
55
+ "ValidationError",
56
+ "__version__",
57
+ ]
File without changes
mopux/_async/client.py ADDED
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from types import TracebackType
5
+
6
+ import httpx
7
+
8
+ from .._retry import RetryPolicy
9
+ from .connector import AsyncConnector, TokenSource
10
+ from .resources import (
11
+ AsyncAuth,
12
+ AsyncComments,
13
+ AsyncNotifications,
14
+ AsyncProjects,
15
+ AsyncTaskGroups,
16
+ AsyncTasks,
17
+ AsyncTeam,
18
+ AsyncTeamInvitations,
19
+ AsyncTouches,
20
+ )
21
+
22
+
23
+ class AsyncMopux:
24
+ """Client of one Mopux installation.
25
+
26
+ Use it as a context manager (``async with AsyncMopux(...) as mopux:``) or call ``aclose()``
27
+ to release the HTTP connections.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ base_url: str | AsyncConnector,
33
+ token: TokenSource = None,
34
+ *,
35
+ timeout: float = 30.0,
36
+ retry: RetryPolicy | None = None,
37
+ user_agent: str | None = None,
38
+ headers: Mapping[str, str] | None = None,
39
+ http_client: httpx.AsyncClient | None = None,
40
+ ) -> None:
41
+ if isinstance(base_url, AsyncConnector):
42
+ self.connector = base_url
43
+ else:
44
+ self.connector = AsyncConnector(
45
+ base_url,
46
+ token,
47
+ timeout=timeout,
48
+ retry=retry,
49
+ user_agent_suffix=user_agent,
50
+ headers=headers,
51
+ http_client=http_client,
52
+ )
53
+ self.auth = AsyncAuth(self.connector)
54
+ self.projects = AsyncProjects(self.connector)
55
+ self.task_groups = AsyncTaskGroups(self.connector)
56
+ self.tasks = AsyncTasks(self.connector)
57
+ self.comments = AsyncComments(self.connector)
58
+ self.notifications = AsyncNotifications(self.connector)
59
+ self.touches = AsyncTouches(self.connector)
60
+ self.team = AsyncTeam(self.connector)
61
+ self.team_invitations = AsyncTeamInvitations(self.connector)
62
+
63
+ @classmethod
64
+ async def login(
65
+ cls,
66
+ base_url: str,
67
+ email: str,
68
+ password: str,
69
+ *,
70
+ token_name: str | None = None,
71
+ timeout: float = 30.0,
72
+ retry: RetryPolicy | None = None,
73
+ user_agent: str | None = None,
74
+ http_client: httpx.AsyncClient | None = None,
75
+ ) -> AsyncMopux:
76
+ """Logs in and returns a client that uses the new token (``client.token``)."""
77
+ anonymous = cls(base_url, timeout=timeout, retry=retry, user_agent=user_agent, http_client=http_client)
78
+ result = await anonymous.auth.login(email, password, token_name)
79
+ return cls(anonymous.connector.with_token(result.token or ""))
80
+
81
+ @property
82
+ def token(self) -> str | None:
83
+ token = self.connector.token
84
+ return token() if callable(token) else token
85
+
86
+ def with_token(self, token: TokenSource) -> AsyncMopux:
87
+ """A client for the same installation (sharing the HTTP connections) with another token."""
88
+ return AsyncMopux(self.connector.with_token(token))
89
+
90
+ async def aclose(self) -> None:
91
+ await self.connector.aclose()
92
+
93
+ async def __aenter__(self) -> AsyncMopux:
94
+ return self
95
+
96
+ async def __aexit__(
97
+ self,
98
+ exc_type: type[BaseException] | None,
99
+ exc: BaseException | None,
100
+ traceback: TracebackType | None,
101
+ ) -> None:
102
+ await self.aclose()
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Callable, Mapping
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from .._base import build_query, map_error, normalize_base_url, unwrap, user_agent
10
+ from .._retry import RetryPolicy
11
+ from ..errors import MopuxConnectionError
12
+
13
+ TokenSource = str | Callable[[], str | None] | None
14
+
15
+
16
+ class AsyncConnector:
17
+ """Sends requests to ``/api/v1``, unwraps ``{success, message, data}`` and raises typed errors."""
18
+
19
+ def __init__(
20
+ self,
21
+ base_url: str,
22
+ token: TokenSource = None,
23
+ *,
24
+ timeout: float = 30.0,
25
+ retry: RetryPolicy | None = None,
26
+ user_agent_suffix: str | None = None,
27
+ headers: Mapping[str, str] | None = None,
28
+ http_client: httpx.AsyncClient | None = None,
29
+ ) -> None:
30
+ self.base_url = normalize_base_url(base_url)
31
+ self.token = token
32
+ self.timeout = timeout
33
+ self.retry = retry or RetryPolicy()
34
+ self.user_agent_suffix = user_agent_suffix
35
+ self.headers = dict(headers or {})
36
+ self._owns_client = http_client is None
37
+ self.http = http_client or httpx.AsyncClient(timeout=timeout)
38
+
39
+ def with_token(self, token: TokenSource) -> AsyncConnector:
40
+ """A connector for the same installation and HTTP client with another token."""
41
+ connector = AsyncConnector(
42
+ self.base_url,
43
+ token,
44
+ timeout=self.timeout,
45
+ retry=self.retry,
46
+ user_agent_suffix=self.user_agent_suffix,
47
+ headers=self.headers,
48
+ http_client=self.http,
49
+ )
50
+ connector._owns_client = False
51
+ return connector
52
+
53
+ async def aclose(self) -> None:
54
+ if self._owns_client:
55
+ await self.http.aclose()
56
+
57
+ async def get(self, path: str, query: Mapping[str, Any] | None = None) -> Any:
58
+ return await self.request("GET", path, query=query)
59
+
60
+ async def post(self, path: str, json: Any = None) -> Any:
61
+ return await self.request("POST", path, json=json)
62
+
63
+ async def patch(self, path: str, json: Any = None) -> Any:
64
+ return await self.request("PATCH", path, json=json)
65
+
66
+ async def delete(self, path: str, query: Mapping[str, Any] | None = None, json: Any = None) -> Any:
67
+ return await self.request("DELETE", path, query=query, json=json)
68
+
69
+ async def request(
70
+ self,
71
+ method: str,
72
+ path: str,
73
+ *,
74
+ query: Mapping[str, Any] | None = None,
75
+ json: Any = None,
76
+ data: Mapping[str, Any] | None = None,
77
+ files: list[tuple[str, tuple[str, bytes, str]]] | None = None,
78
+ ) -> Any:
79
+ method = method.upper()
80
+ path = path.lstrip("/")
81
+ query_string = build_query(query or {})
82
+ url = f"{self.base_url}/api/v1/{path}" + (f"?{query_string}" if query_string else "")
83
+ headers = {**self.headers, "Accept": "application/json", "User-Agent": user_agent(self.user_agent_suffix)}
84
+ token = self.token() if callable(self.token) else self.token
85
+ if token:
86
+ headers["Authorization"] = f"Bearer {token}"
87
+
88
+ attempt = 0
89
+ while True:
90
+ try:
91
+ response = await self.http.request(
92
+ method,
93
+ url,
94
+ headers=headers,
95
+ json=json if files is None else None,
96
+ data=data if files is not None else None,
97
+ files=files,
98
+ timeout=self.timeout,
99
+ )
100
+ except httpx.TransportError as error:
101
+ delay = self.retry.delay_after_connection_error(method, attempt)
102
+ if delay is None:
103
+ raise MopuxConnectionError(method, path, error) from error
104
+ await asyncio.sleep(delay)
105
+ attempt += 1
106
+ continue
107
+
108
+ if response.is_success:
109
+ return unwrap(method, path, response)
110
+
111
+ delay = self.retry.delay_after_response(
112
+ method, response.status_code, response.headers.get("retry-after"), attempt
113
+ )
114
+ if delay is not None:
115
+ await asyncio.sleep(delay)
116
+ attempt += 1
117
+ continue
118
+
119
+ raise map_error(method, path, response)
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator, Awaitable, Callable
4
+ from typing import TypeVar
5
+
6
+ from ..page import Page
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ async def iterate_pages(fetch: Callable[[int], Awaitable[Page[T]]], first_page: int = 1) -> AsyncIterator[T]:
12
+ """Walks every page lazily, yielding items one by one; stops if the API repeats a page."""
13
+ page: int | None = first_page
14
+ while page is not None:
15
+ result = await fetch(page)
16
+ for item in result.items:
17
+ yield item
18
+ next_page = result.next_page()
19
+ page = next_page if next_page is not None and next_page > page else None