qubitclient 0.0.0.1__py3-none-any.whl → 0.0.1__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.

Potentially problematic release.


This version of qubitclient might be problematic. Click here for more details.

Files changed (49) hide show
  1. qubitclient/QubitSeg.py +3 -3
  2. qubitclient/__init__.py +2 -0
  3. qubitclient/curve/curve_type.py +15 -0
  4. qubitclient/scope/scope.py +51 -0
  5. qubitclient/scope/scope_api/__init__.py +8 -0
  6. qubitclient/scope/scope_api/api/__init__.py +1 -0
  7. qubitclient/scope/scope_api/api/defined_tasks/__init__.py +1 -0
  8. qubitclient/scope/scope_api/api/defined_tasks/get_task_result_api_v1_tasks_demo_pk_get.py +155 -0
  9. qubitclient/scope/scope_api/api/defined_tasks/get_task_result_api_v1_tasks_scope_pk_get.py +155 -0
  10. qubitclient/scope/scope_api/api/defined_tasks/optpipulse_api_v1_tasks_scope_optpipulse_post.py +218 -0
  11. qubitclient/scope/scope_api/api/defined_tasks/rabi_api_v1_tasks_scope_rabi_post.py +218 -0
  12. qubitclient/scope/scope_api/api/defined_tasks/rabicos_api_v1_tasks_scope_rabicospeak_post.py +218 -0
  13. qubitclient/scope/scope_api/api/defined_tasks/s21peak_api_v1_tasks_scope_s21peak_post.py +218 -0
  14. qubitclient/scope/scope_api/api/defined_tasks/s21vflux_api_v1_tasks_scope_s21vflux_post.py +218 -0
  15. qubitclient/scope/scope_api/api/defined_tasks/singleshot_api_v1_tasks_scope_singleshot_post.py +218 -0
  16. qubitclient/scope/scope_api/api/defined_tasks/spectrum_api_v1_tasks_scope_spectrum_post.py +218 -0
  17. qubitclient/scope/scope_api/api/defined_tasks/t1fit_api_v1_tasks_scope_t1fit_post.py +218 -0
  18. qubitclient/scope/scope_api/api/defined_tasks/t1fit_api_v1_tasks_scope_t2fit_post.py +218 -0
  19. qubitclient/scope/scope_api/client.py +268 -0
  20. qubitclient/scope/scope_api/errors.py +16 -0
  21. qubitclient/scope/scope_api/models/__init__.py +27 -0
  22. qubitclient/scope/scope_api/models/body_optpipulse_api_v1_tasks_scope_optpipulse_post.py +83 -0
  23. qubitclient/scope/scope_api/models/body_rabi_api_v1_tasks_scope_rabi_post.py +83 -0
  24. qubitclient/scope/scope_api/models/body_rabicos_api_v1_tasks_scope_rabicospeak_post.py +83 -0
  25. qubitclient/scope/scope_api/models/body_s21_peak_api_v1_tasks_scope_s21_peak_post.py +83 -0
  26. qubitclient/scope/scope_api/models/body_s21_vflux_api_v1_tasks_scope_s21_vflux_post.py +83 -0
  27. qubitclient/scope/scope_api/models/body_singleshot_api_v1_tasks_scope_singleshot_post.py +83 -0
  28. qubitclient/scope/scope_api/models/body_spectrum_api_v1_tasks_scope_spectrum_post.py +83 -0
  29. qubitclient/scope/scope_api/models/body_t1_fit_api_v1_tasks_scope_t1_fit_post.py +83 -0
  30. qubitclient/scope/scope_api/models/body_t1_fit_api_v1_tasks_scope_t2_fit_post.py +83 -0
  31. qubitclient/scope/scope_api/models/http_validation_error.py +75 -0
  32. qubitclient/scope/scope_api/models/validation_error.py +88 -0
  33. qubitclient/scope/scope_api/py.typed +1 -0
  34. qubitclient/scope/scope_api/types.py +54 -0
  35. qubitclient/scope/task.py +140 -0
  36. qubitclient/scope/utils/__init__.py +0 -0
  37. qubitclient/scope/utils/data_parser.py +20 -0
  38. qubitclient/utils/data_convert.py +112 -0
  39. qubitclient/utils/data_parser.py +41 -0
  40. qubitclient/utils/request_tool.py +41 -0
  41. qubitclient/utils/result_parser.py +55 -0
  42. qubitclient-0.0.1.dist-info/METADATA +106 -0
  43. qubitclient-0.0.1.dist-info/RECORD +47 -0
  44. qubitclient-0.0.0.1.dist-info/METADATA +0 -35
  45. qubitclient-0.0.0.1.dist-info/RECORD +0 -8
  46. {qubitclient-0.0.0.1.dist-info → qubitclient-0.0.1.dist-info}/WHEEL +0 -0
  47. {qubitclient-0.0.0.1.dist-info → qubitclient-0.0.1.dist-info}/licenses/LICENSE +0 -0
  48. {qubitclient-0.0.0.1.dist-info → qubitclient-0.0.1.dist-info}/top_level.txt +0 -0
  49. {qubitclient-0.0.0.1.dist-info → qubitclient-0.0.1.dist-info}/zip-safe +0 -0
@@ -0,0 +1,218 @@
1
+ from http import HTTPStatus
2
+ from typing import Any, Optional, Union
3
+
4
+ import httpx
5
+
6
+ from ... import errors
7
+ from ...client import AuthenticatedClient, Client
8
+ from ...models.body_t1_fit_api_v1_tasks_scope_t1_fit_post import BodyT1FitApiV1TasksScopeT1FitPost
9
+ from ...models.http_validation_error import HTTPValidationError
10
+ from ...types import UNSET, Response, Unset
11
+
12
+
13
+ def _get_kwargs(
14
+ *,
15
+ body: BodyT1FitApiV1TasksScopeT1FitPost,
16
+ type_: Union[Unset, str] = "t1fit",
17
+ ) -> dict[str, Any]:
18
+ headers: dict[str, Any] = {}
19
+
20
+ params: dict[str, Any] = {}
21
+
22
+ params["type"] = type_
23
+
24
+ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
25
+
26
+ _kwargs: dict[str, Any] = {
27
+ "method": "post",
28
+ "url": "/api/v1/tasks/scope/t1fit",
29
+ "params": params,
30
+ }
31
+
32
+ _kwargs["files"] = body.to_multipart()
33
+
34
+ _kwargs["headers"] = headers
35
+ return _kwargs
36
+
37
+
38
+ def _parse_response(
39
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
40
+ ) -> Optional[Union[Any, HTTPValidationError]]:
41
+ if response.status_code == 200:
42
+ response_200 = response.json()
43
+ return response_200
44
+
45
+ if response.status_code == 422:
46
+ response_422 = HTTPValidationError.from_dict(response.json())
47
+
48
+ return response_422
49
+
50
+ if client.raise_on_unexpected_status:
51
+ raise errors.UnexpectedStatus(response.status_code, response.content)
52
+ else:
53
+ return None
54
+
55
+
56
+ def _build_response(
57
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
58
+ ) -> Response[Union[Any, HTTPValidationError]]:
59
+ return Response(
60
+ status_code=HTTPStatus(response.status_code),
61
+ content=response.content,
62
+ headers=response.headers,
63
+ parsed=_parse_response(client=client, response=response),
64
+ )
65
+
66
+
67
+ def sync_detailed(
68
+ *,
69
+ client: Union[AuthenticatedClient, Client],
70
+ body: BodyT1FitApiV1TasksScopeT1FitPost,
71
+ type_: Union[Unset, str] = "t1fit",
72
+ ) -> Response[Union[Any, HTTPValidationError]]:
73
+ r"""T1Fit
74
+
75
+ t1 fit
76
+
77
+ Args:
78
+ files: 上传的.npy文件列表
79
+ type: 任务类型,默认为\"s21peak\"
80
+
81
+ Returns:
82
+ dict: 包含检测结果的字典
83
+
84
+ Args:
85
+ type_ (Union[Unset, str]): 任务类型 Default: 't1fit'.
86
+ body (BodyT1FitApiV1TasksScopeT1FitPost):
87
+
88
+ Raises:
89
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
90
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
91
+
92
+ Returns:
93
+ Response[Union[Any, HTTPValidationError]]
94
+ """
95
+
96
+ kwargs = _get_kwargs(
97
+ body=body,
98
+ type_=type_,
99
+ )
100
+
101
+ response = client.get_httpx_client().request(
102
+ **kwargs,
103
+ )
104
+
105
+ return _build_response(client=client, response=response)
106
+
107
+
108
+ def sync(
109
+ *,
110
+ client: Union[AuthenticatedClient, Client],
111
+ body: BodyT1FitApiV1TasksScopeT1FitPost,
112
+ type_: Union[Unset, str] = "t1fit",
113
+ ) -> Optional[Union[Any, HTTPValidationError]]:
114
+ r"""T1Fit
115
+
116
+ t1 fit
117
+
118
+ Args:
119
+ files: 上传的.npy文件列表
120
+ type: 任务类型,默认为\"s21peak\"
121
+
122
+ Returns:
123
+ dict: 包含检测结果的字典
124
+
125
+ Args:
126
+ type_ (Union[Unset, str]): 任务类型 Default: 't1fit'.
127
+ body (BodyT1FitApiV1TasksScopeT1FitPost):
128
+
129
+ Raises:
130
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
131
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
132
+
133
+ Returns:
134
+ Union[Any, HTTPValidationError]
135
+ """
136
+
137
+ return sync_detailed(
138
+ client=client,
139
+ body=body,
140
+ type_=type_,
141
+ ).parsed
142
+
143
+
144
+ async def asyncio_detailed(
145
+ *,
146
+ client: Union[AuthenticatedClient, Client],
147
+ body: BodyT1FitApiV1TasksScopeT1FitPost,
148
+ type_: Union[Unset, str] = "t1fit",
149
+ ) -> Response[Union[Any, HTTPValidationError]]:
150
+ r"""T1Fit
151
+
152
+ t1 fit
153
+
154
+ Args:
155
+ files: 上传的.npy文件列表
156
+ type: 任务类型,默认为\"s21peak\"
157
+
158
+ Returns:
159
+ dict: 包含检测结果的字典
160
+
161
+ Args:
162
+ type_ (Union[Unset, str]): 任务类型 Default: 't1fit'.
163
+ body (BodyT1FitApiV1TasksScopeT1FitPost):
164
+
165
+ Raises:
166
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
167
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
168
+
169
+ Returns:
170
+ Response[Union[Any, HTTPValidationError]]
171
+ """
172
+
173
+ kwargs = _get_kwargs(
174
+ body=body,
175
+ type_=type_,
176
+ )
177
+
178
+ response = await client.get_async_httpx_client().request(**kwargs)
179
+
180
+ return _build_response(client=client, response=response)
181
+
182
+
183
+ async def asyncio(
184
+ *,
185
+ client: Union[AuthenticatedClient, Client],
186
+ body: BodyT1FitApiV1TasksScopeT1FitPost,
187
+ type_: Union[Unset, str] = "t1fit",
188
+ ) -> Optional[Union[Any, HTTPValidationError]]:
189
+ r"""T1Fit
190
+
191
+ t1 fit
192
+
193
+ Args:
194
+ files: 上传的.npy文件列表
195
+ type: 任务类型,默认为\"s21peak\"
196
+
197
+ Returns:
198
+ dict: 包含检测结果的字典
199
+
200
+ Args:
201
+ type_ (Union[Unset, str]): 任务类型 Default: 't1fit'.
202
+ body (BodyT1FitApiV1TasksScopeT1FitPost):
203
+
204
+ Raises:
205
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
206
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
207
+
208
+ Returns:
209
+ Union[Any, HTTPValidationError]
210
+ """
211
+
212
+ return (
213
+ await asyncio_detailed(
214
+ client=client,
215
+ body=body,
216
+ type_=type_,
217
+ )
218
+ ).parsed
@@ -0,0 +1,218 @@
1
+ from http import HTTPStatus
2
+ from typing import Any, Optional, Union
3
+
4
+ import httpx
5
+
6
+ from ... import errors
7
+ from ...client import AuthenticatedClient, Client
8
+ from ...models.body_t1_fit_api_v1_tasks_scope_t2_fit_post import BodyT1FitApiV1TasksScopeT2FitPost
9
+ from ...models.http_validation_error import HTTPValidationError
10
+ from ...types import UNSET, Response, Unset
11
+
12
+
13
+ def _get_kwargs(
14
+ *,
15
+ body: BodyT1FitApiV1TasksScopeT2FitPost,
16
+ type_: Union[Unset, str] = "t2fit",
17
+ ) -> dict[str, Any]:
18
+ headers: dict[str, Any] = {}
19
+
20
+ params: dict[str, Any] = {}
21
+
22
+ params["type"] = type_
23
+
24
+ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
25
+
26
+ _kwargs: dict[str, Any] = {
27
+ "method": "post",
28
+ "url": "/api/v1/tasks/scope/t2fit",
29
+ "params": params,
30
+ }
31
+
32
+ _kwargs["files"] = body.to_multipart()
33
+
34
+ _kwargs["headers"] = headers
35
+ return _kwargs
36
+
37
+
38
+ def _parse_response(
39
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
40
+ ) -> Optional[Union[Any, HTTPValidationError]]:
41
+ if response.status_code == 200:
42
+ response_200 = response.json()
43
+ return response_200
44
+
45
+ if response.status_code == 422:
46
+ response_422 = HTTPValidationError.from_dict(response.json())
47
+
48
+ return response_422
49
+
50
+ if client.raise_on_unexpected_status:
51
+ raise errors.UnexpectedStatus(response.status_code, response.content)
52
+ else:
53
+ return None
54
+
55
+
56
+ def _build_response(
57
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
58
+ ) -> Response[Union[Any, HTTPValidationError]]:
59
+ return Response(
60
+ status_code=HTTPStatus(response.status_code),
61
+ content=response.content,
62
+ headers=response.headers,
63
+ parsed=_parse_response(client=client, response=response),
64
+ )
65
+
66
+
67
+ def sync_detailed(
68
+ *,
69
+ client: Union[AuthenticatedClient, Client],
70
+ body: BodyT1FitApiV1TasksScopeT2FitPost,
71
+ type_: Union[Unset, str] = "t2fit",
72
+ ) -> Response[Union[Any, HTTPValidationError]]:
73
+ r"""T1Fit
74
+
75
+ t2 fit
76
+
77
+ Args:
78
+ files: 上传的.npy文件列表
79
+ type: 任务类型,默认为\"s21peak\"
80
+
81
+ Returns:
82
+ dict: 包含检测结果的字典
83
+
84
+ Args:
85
+ type_ (Union[Unset, str]): 任务类型 Default: 't2fit'.
86
+ body (BodyT1FitApiV1TasksScopeT2FitPost):
87
+
88
+ Raises:
89
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
90
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
91
+
92
+ Returns:
93
+ Response[Union[Any, HTTPValidationError]]
94
+ """
95
+
96
+ kwargs = _get_kwargs(
97
+ body=body,
98
+ type_=type_,
99
+ )
100
+
101
+ response = client.get_httpx_client().request(
102
+ **kwargs,
103
+ )
104
+
105
+ return _build_response(client=client, response=response)
106
+
107
+
108
+ def sync(
109
+ *,
110
+ client: Union[AuthenticatedClient, Client],
111
+ body: BodyT1FitApiV1TasksScopeT2FitPost,
112
+ type_: Union[Unset, str] = "t2fit",
113
+ ) -> Optional[Union[Any, HTTPValidationError]]:
114
+ r"""T1Fit
115
+
116
+ t2 fit
117
+
118
+ Args:
119
+ files: 上传的.npy文件列表
120
+ type: 任务类型,默认为\"s21peak\"
121
+
122
+ Returns:
123
+ dict: 包含检测结果的字典
124
+
125
+ Args:
126
+ type_ (Union[Unset, str]): 任务类型 Default: 't2fit'.
127
+ body (BodyT1FitApiV1TasksScopeT2FitPost):
128
+
129
+ Raises:
130
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
131
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
132
+
133
+ Returns:
134
+ Union[Any, HTTPValidationError]
135
+ """
136
+
137
+ return sync_detailed(
138
+ client=client,
139
+ body=body,
140
+ type_=type_,
141
+ ).parsed
142
+
143
+
144
+ async def asyncio_detailed(
145
+ *,
146
+ client: Union[AuthenticatedClient, Client],
147
+ body: BodyT1FitApiV1TasksScopeT2FitPost,
148
+ type_: Union[Unset, str] = "t2fit",
149
+ ) -> Response[Union[Any, HTTPValidationError]]:
150
+ r"""T1Fit
151
+
152
+ t2 fit
153
+
154
+ Args:
155
+ files: 上传的.npy文件列表
156
+ type: 任务类型,默认为\"s21peak\"
157
+
158
+ Returns:
159
+ dict: 包含检测结果的字典
160
+
161
+ Args:
162
+ type_ (Union[Unset, str]): 任务类型 Default: 't2fit'.
163
+ body (BodyT1FitApiV1TasksScopeT2FitPost):
164
+
165
+ Raises:
166
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
167
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
168
+
169
+ Returns:
170
+ Response[Union[Any, HTTPValidationError]]
171
+ """
172
+
173
+ kwargs = _get_kwargs(
174
+ body=body,
175
+ type_=type_,
176
+ )
177
+
178
+ response = await client.get_async_httpx_client().request(**kwargs)
179
+
180
+ return _build_response(client=client, response=response)
181
+
182
+
183
+ async def asyncio(
184
+ *,
185
+ client: Union[AuthenticatedClient, Client],
186
+ body: BodyT1FitApiV1TasksScopeT2FitPost,
187
+ type_: Union[Unset, str] = "t2fit",
188
+ ) -> Optional[Union[Any, HTTPValidationError]]:
189
+ r"""T1Fit
190
+
191
+ t2 fit
192
+
193
+ Args:
194
+ files: 上传的.npy文件列表
195
+ type: 任务类型,默认为\"s21peak\"
196
+
197
+ Returns:
198
+ dict: 包含检测结果的字典
199
+
200
+ Args:
201
+ type_ (Union[Unset, str]): 任务类型 Default: 't2fit'.
202
+ body (BodyT1FitApiV1TasksScopeT2FitPost):
203
+
204
+ Raises:
205
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
206
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
207
+
208
+ Returns:
209
+ Union[Any, HTTPValidationError]
210
+ """
211
+
212
+ return (
213
+ await asyncio_detailed(
214
+ client=client,
215
+ body=body,
216
+ type_=type_,
217
+ )
218
+ ).parsed
@@ -0,0 +1,268 @@
1
+ import ssl
2
+ from typing import Any, Optional, Union
3
+
4
+ import httpx
5
+ from attrs import define, evolve, field
6
+
7
+
8
+ @define
9
+ class Client:
10
+ """A class for keeping track of data related to the API
11
+
12
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
13
+
14
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
15
+
16
+ ``cookies``: A dictionary of cookies to be sent with every request
17
+
18
+ ``headers``: A dictionary of headers to be sent with every request
19
+
20
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
21
+ httpx.TimeoutException if this is exceeded.
22
+
23
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
24
+ but can be set to False for testing purposes.
25
+
26
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
27
+
28
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
29
+
30
+
31
+ Attributes:
32
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
33
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
34
+ argument to the constructor.
35
+ """
36
+
37
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
38
+ _base_url: str = field(alias="base_url")
39
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
40
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
41
+ _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
42
+ _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
43
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
44
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
45
+ _client: Optional[httpx.Client] = field(default=None, init=False)
46
+ _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
47
+
48
+ def with_headers(self, headers: dict[str, str]) -> "Client":
49
+ """Get a new client matching this one with additional headers"""
50
+ if self._client is not None:
51
+ self._client.headers.update(headers)
52
+ if self._async_client is not None:
53
+ self._async_client.headers.update(headers)
54
+ return evolve(self, headers={**self._headers, **headers})
55
+
56
+ def with_cookies(self, cookies: dict[str, str]) -> "Client":
57
+ """Get a new client matching this one with additional cookies"""
58
+ if self._client is not None:
59
+ self._client.cookies.update(cookies)
60
+ if self._async_client is not None:
61
+ self._async_client.cookies.update(cookies)
62
+ return evolve(self, cookies={**self._cookies, **cookies})
63
+
64
+ def with_timeout(self, timeout: httpx.Timeout) -> "Client":
65
+ """Get a new client matching this one with a new timeout (in seconds)"""
66
+ if self._client is not None:
67
+ self._client.timeout = timeout
68
+ if self._async_client is not None:
69
+ self._async_client.timeout = timeout
70
+ return evolve(self, timeout=timeout)
71
+
72
+ def set_httpx_client(self, client: httpx.Client) -> "Client":
73
+ """Manually set the underlying httpx.Client
74
+
75
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
76
+ """
77
+ self._client = client
78
+ return self
79
+
80
+ def get_httpx_client(self) -> httpx.Client:
81
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
82
+ if self._client is None:
83
+ self._client = httpx.Client(
84
+ base_url=self._base_url,
85
+ cookies=self._cookies,
86
+ headers=self._headers,
87
+ timeout=self._timeout,
88
+ verify=self._verify_ssl,
89
+ follow_redirects=self._follow_redirects,
90
+ **self._httpx_args,
91
+ )
92
+ return self._client
93
+
94
+ def __enter__(self) -> "Client":
95
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
96
+ self.get_httpx_client().__enter__()
97
+ return self
98
+
99
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
100
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
101
+ self.get_httpx_client().__exit__(*args, **kwargs)
102
+
103
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
104
+ """Manually the underlying httpx.AsyncClient
105
+
106
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
107
+ """
108
+ self._async_client = async_client
109
+ return self
110
+
111
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
112
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
113
+ if self._async_client is None:
114
+ self._async_client = httpx.AsyncClient(
115
+ base_url=self._base_url,
116
+ cookies=self._cookies,
117
+ headers=self._headers,
118
+ timeout=self._timeout,
119
+ verify=self._verify_ssl,
120
+ follow_redirects=self._follow_redirects,
121
+ **self._httpx_args,
122
+ )
123
+ return self._async_client
124
+
125
+ async def __aenter__(self) -> "Client":
126
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
127
+ await self.get_async_httpx_client().__aenter__()
128
+ return self
129
+
130
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
131
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
132
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)
133
+
134
+
135
+ @define
136
+ class AuthenticatedClient:
137
+ """A Client which has been authenticated for use on secured endpoints
138
+
139
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
140
+
141
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
142
+
143
+ ``cookies``: A dictionary of cookies to be sent with every request
144
+
145
+ ``headers``: A dictionary of headers to be sent with every request
146
+
147
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
148
+ httpx.TimeoutException if this is exceeded.
149
+
150
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
151
+ but can be set to False for testing purposes.
152
+
153
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
154
+
155
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
156
+
157
+
158
+ Attributes:
159
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
160
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
161
+ argument to the constructor.
162
+ token: The token to use for authentication
163
+ prefix: The prefix to use for the Authorization header
164
+ auth_header_name: The name of the Authorization header
165
+ """
166
+
167
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
168
+ _base_url: str = field(alias="base_url")
169
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
170
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
171
+ _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
172
+ _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
173
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
174
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
175
+ _client: Optional[httpx.Client] = field(default=None, init=False)
176
+ _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
177
+
178
+ token: str
179
+ prefix: str = "Bearer"
180
+ auth_header_name: str = "Authorization"
181
+
182
+ def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
183
+ """Get a new client matching this one with additional headers"""
184
+ if self._client is not None:
185
+ self._client.headers.update(headers)
186
+ if self._async_client is not None:
187
+ self._async_client.headers.update(headers)
188
+ return evolve(self, headers={**self._headers, **headers})
189
+
190
+ def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
191
+ """Get a new client matching this one with additional cookies"""
192
+ if self._client is not None:
193
+ self._client.cookies.update(cookies)
194
+ if self._async_client is not None:
195
+ self._async_client.cookies.update(cookies)
196
+ return evolve(self, cookies={**self._cookies, **cookies})
197
+
198
+ def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
199
+ """Get a new client matching this one with a new timeout (in seconds)"""
200
+ if self._client is not None:
201
+ self._client.timeout = timeout
202
+ if self._async_client is not None:
203
+ self._async_client.timeout = timeout
204
+ return evolve(self, timeout=timeout)
205
+
206
+ def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
207
+ """Manually set the underlying httpx.Client
208
+
209
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
210
+ """
211
+ self._client = client
212
+ return self
213
+
214
+ def get_httpx_client(self) -> httpx.Client:
215
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
216
+ if self._client is None:
217
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
218
+ self._client = httpx.Client(
219
+ base_url=self._base_url,
220
+ cookies=self._cookies,
221
+ headers=self._headers,
222
+ timeout=self._timeout,
223
+ verify=self._verify_ssl,
224
+ follow_redirects=self._follow_redirects,
225
+ **self._httpx_args,
226
+ )
227
+ return self._client
228
+
229
+ def __enter__(self) -> "AuthenticatedClient":
230
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
231
+ self.get_httpx_client().__enter__()
232
+ return self
233
+
234
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
235
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
236
+ self.get_httpx_client().__exit__(*args, **kwargs)
237
+
238
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":
239
+ """Manually the underlying httpx.AsyncClient
240
+
241
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
242
+ """
243
+ self._async_client = async_client
244
+ return self
245
+
246
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
247
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
248
+ if self._async_client is None:
249
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
250
+ self._async_client = httpx.AsyncClient(
251
+ base_url=self._base_url,
252
+ cookies=self._cookies,
253
+ headers=self._headers,
254
+ timeout=self._timeout,
255
+ verify=self._verify_ssl,
256
+ follow_redirects=self._follow_redirects,
257
+ **self._httpx_args,
258
+ )
259
+ return self._async_client
260
+
261
+ async def __aenter__(self) -> "AuthenticatedClient":
262
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
263
+ await self.get_async_httpx_client().__aenter__()
264
+ return self
265
+
266
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
267
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
268
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)