-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.py
More file actions
174 lines (140 loc) · 5.45 KB
/
interface.py
File metadata and controls
174 lines (140 loc) · 5.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""campus.client.interface
Interface descriptions for the Campus client interface.
This interface is designed to:
- wrap `flask.testing.FlaskClient`
- wrap most common client interfaces e.g. `requests`
- provide a common Response interface that wraps `werkzeug.test.TestResponse,
`requests.Response`, etc
- so aa to enable WSGI hooks or unit testing with a local WSGI app.
"""
from typing import Any, Optional
from .json_client import JsonClient, JsonDict, JsonResponse
# Use char constant to avoid quoting-related syntax errors
SLASH = "/"
class ResourceRoot:
"""Root of all resources.
This class is used to group all top-level resources together.
"""
_client: Optional[JsonClient] = None
url_prefix: str
def __init__(self, json_client: Optional[JsonClient] = None):
self._client = json_client
@property
def base_url(self) -> str:
"""Get the base URL for this resource root."""
if not self._client:
raise AttributeError("No client defined")
return self._client.base_url
@property
def client(self) -> JsonClient:
"""Get the JsonClient associated with this resource root."""
if not self._client:
raise AttributeError(
f"No client defined for {self}"
)
return self._client
def make_path(self, part: str | None = None) -> str:
"""Create a full path for the resource root or a sub-resource.
Args:
part (str | None): Optional sub-resource or action path.
Returns:
str: Full path for the resource root or sub-resource.
"""
if part:
return f"/{self.url_prefix.lstrip(SLASH)}/{part.lstrip(SLASH)}"
else:
return f"/{self.url_prefix.lstrip(SLASH)}"
def make_url(self) -> str:
"""Create a full path for the resource root."""
return f"{self.base_url}/{self.url_prefix.lstrip(SLASH)}"
class ResourceCollection:
"""Collection of resources.
This class is used to group related resources together.
"""
_client: Optional[JsonClient] = None
path: str
root: ResourceRoot
def __init__(
self,
client: Optional[JsonClient] = None,
*,
root: ResourceRoot
):
self._client = client
self.root = root
@property
def client(self) -> JsonClient:
"""Get the JsonClient associated with this resource."""
if self._client:
return self._client
if self.root.client:
return self.root.client
raise AttributeError(f"No client defined for {self}")
def make_path(self, part: str | None = None, end_slash: bool = True) -> str:
"""Create a full path for a resource collection.
Args:
part: Optional sub-resource or action path.
end_slash: Whether to add a trailing slash (default: True for collections).
Returns:
Full path for the resource collection or sub-resource.
"""
if part:
base = f"/{self.root.make_path(self.path).strip(SLASH)}/{part.strip(SLASH)}"
return f"{base}/" if end_slash else base
else:
return f"/{self.root.make_path(self.path).strip(SLASH)}/"
def make_url(self, part: str | None = None) -> str:
"""Create a full URL for a sub-resource or action."""
return f"{self.root.make_url()}{self.make_path(part)}"
class Resource:
"""Resource class that represents API resources
The resource class uses a JsonClient instance to handle all API requests.
It only tracks the path of the current resource.
"""
_client: Optional[JsonClient] = None
parent: "Resource | ResourceCollection"
path: str
def __init__(
self,
*parts: str,
parent: "Resource | ResourceCollection",
client: Optional[JsonClient] = None,
):
self._client = client
self.parent = parent
self.path = parent.make_path(SLASH.join(parts))
def __repr__(self) -> str:
return f"Resource(client={self.client}, path={self.path})"
def __str__(self) -> str:
return self.path
@property
def client(self) -> JsonClient:
"""Get the JsonClient associated with this resource."""
if self._client:
return self._client
if self.parent and self.parent.client:
return self.parent.client
raise AttributeError(f"No client defined for {self}")
def _process_response(self, response: JsonResponse) -> JsonResponse | Any:
"""Process response based on raw setting.
If raw=True, returns JsonResponse directly.
If raw=False, calls raise_for_status() then returns response.json().
"""
response.raise_for_status()
return response.json()
def make_path(self, part: str | None = None, end_slash=False) -> str:
"""Create a full path for a sub-resource or action."""
if part:
full_path = (
f"/{self.path.strip(SLASH)}"
f"/{part.strip(SLASH)}"
f"{SLASH if end_slash else ''}"
)
else:
full_path = f"/{self.path.lstrip(SLASH)}"
if end_slash and not full_path.endswith(SLASH):
full_path += SLASH
return full_path
def make_url(self, part: str | None = None) -> str:
"""Create a full URL for a sub-resource or action."""
return f"{self.parent.make_url()}{self.make_path(part)}"