ansys-hps-data-transfer-client 0.5.dev0__tar.gz → 0.6.dev0__tar.gz

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.
Files changed (21) hide show
  1. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/PKG-INFO +11 -11
  2. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/pyproject.toml +11 -11
  3. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/api/api.py +15 -5
  4. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/api/async_api.py +5 -2
  5. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/api/handler.py +5 -1
  6. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/binary.py +18 -10
  7. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/client.py +15 -4
  8. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/models/models.py +63 -2
  9. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/token.py +16 -4
  10. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/LICENSE +0 -0
  11. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/README.rst +0 -0
  12. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/__init__.py +0 -0
  13. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/__version__.py +0 -0
  14. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/api/__init__.py +0 -0
  15. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/api/retry.py +0 -0
  16. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/authenticate.py +0 -0
  17. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/exceptions.py +0 -0
  18. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/models/__init__.py +0 -0
  19. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/utils/__init__.py +0 -0
  20. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/utils/jitter.py +0 -0
  21. {ansys_hps_data_transfer_client-0.5.dev0 → ansys_hps_data_transfer_client-0.6.dev0}/src/ansys/hps/data_transfer/client/utils/otel_config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: ansys-hps-data-transfer-client
3
- Version: 0.5.dev0
3
+ Version: 0.6.dev0
4
4
  Summary: Python client library for hps data transfer service
5
5
  Author-email: "ANSYS, Inc." <pyansys.core@ansys.com>
6
6
  Maintainer-email: "ANSYS, Inc." <pyansys.core@ansys.com>
@@ -21,13 +21,13 @@ Requires-Dist: portend>=3.2.0
21
21
  Requires-Dist: filelock>=3.14.0
22
22
  Requires-Dist: psutil>=5.9.1
23
23
  Requires-Dist: asyncio-atexit>=1.0.0
24
- Requires-Dist: build==1.4.2 ; extra == "build"
25
- Requires-Dist: twine==6.2.0 ; extra == "build"
24
+ Requires-Dist: build==1.5.1 ; extra == "build"
25
+ Requires-Dist: twine==7.0.0 ; extra == "build"
26
26
  Requires-Dist: wheel ; extra == "build"
27
- Requires-Dist: datamodel-code-generator==0.55.0 ; extra == "build"
28
- Requires-Dist: pre-commit==4.5.1 ; extra == "build"
27
+ Requires-Dist: datamodel-code-generator==0.71.0 ; extra == "build"
28
+ Requires-Dist: pre-commit==4.6.1 ; extra == "build"
29
29
  Requires-Dist: importlib_metadata>=7.0 ; extra == "build"
30
- Requires-Dist: ansys-sphinx-theme==1.7.2 ; extra == "doc"
30
+ Requires-Dist: ansys-sphinx-theme==1.9.0 ; extra == "doc"
31
31
  Requires-Dist: autodoc_pydantic==2.2.0 ; extra == "doc"
32
32
  Requires-Dist: numpydoc==1.10.0 ; extra == "doc"
33
33
  Requires-Dist: Sphinx==8.1.3 ; extra == "doc"
@@ -35,17 +35,17 @@ Requires-Dist: sphinx-autoapi==3.8.0 ; extra == "doc"
35
35
  Requires-Dist: sphinx-copybutton==0.5.2 ; extra == "doc"
36
36
  Requires-Dist: sphinx_design==0.6.1 ; extra == "doc"
37
37
  Requires-Dist: sphinx-jinja==2.0.2 ; extra == "doc"
38
- Requires-Dist: sphinx-gallery==0.20.0 ; extra == "doc"
38
+ Requires-Dist: sphinx-gallery==0.21.0 ; extra == "doc"
39
39
  Requires-Dist: typer>=0.9.0 ; extra == "example"
40
- Requires-Dist: pytest==9.0.2 ; extra == "tests"
40
+ Requires-Dist: pytest==9.1.1 ; extra == "tests"
41
41
  Requires-Dist: pytest-cov==7.1.0 ; extra == "tests"
42
42
  Requires-Dist: pytest-timeout==2.4.0 ; extra == "tests"
43
43
  Requires-Dist: pytest-mock-resources[redis]==2.12.4 ; extra == "tests"
44
- Requires-Dist: pytest-rerunfailures==16.1 ; extra == "tests"
45
- Requires-Dist: pytest-asyncio==1.3.0 ; extra == "tests"
44
+ Requires-Dist: pytest-rerunfailures==16.4 ; extra == "tests"
45
+ Requires-Dist: pytest-asyncio==1.4.0 ; extra == "tests"
46
46
  Requires-Dist: python-keycloak==7.1.1 ; extra == "tests"
47
47
  Requires-Dist: python-slugify>=8.0.4 ; extra == "tests"
48
- Requires-Dist: tox==4.50.3 ; extra == "tests"
48
+ Requires-Dist: tox==4.58.0 ; extra == "tests"
49
49
  Project-URL: Documentation, https://data-transfer.hps.docs.pyansys.com
50
50
  Project-URL: Homepage, https://github.com/ansys/pyhps-data-transfer/
51
51
  Project-URL: Source, https://github.com/ansys/pyhps-data-transfer/
@@ -5,7 +5,7 @@ build-backend = "flit_core.buildapi"
5
5
  [project]
6
6
  # Check https://flit.readthedocs.io/en/latest/pyproject_toml.html for all available sections
7
7
  name = "ansys-hps-data-transfer-client"
8
- version = "0.5.dev0"
8
+ version = "0.6.dev0"
9
9
  description = "Python client library for hps data transfer service"
10
10
  readme = "README.rst"
11
11
  requires-python = ">=3.10,<4.0"
@@ -39,18 +39,18 @@ dependencies = [
39
39
 
40
40
  [project.optional-dependencies]
41
41
  tests = [
42
- "pytest==9.0.2",
42
+ "pytest==9.1.1",
43
43
  "pytest-cov==7.1.0",
44
44
  "pytest-timeout==2.4.0",
45
45
  "pytest-mock-resources[redis]==2.12.4",
46
- "pytest-rerunfailures==16.1",
47
- "pytest-asyncio==1.3.0",
46
+ "pytest-rerunfailures==16.4",
47
+ "pytest-asyncio==1.4.0",
48
48
  "python-keycloak==7.1.1",
49
49
  "python-slugify>=8.0.4",
50
- "tox==4.50.3",
50
+ "tox==4.58.0",
51
51
  ]
52
52
  doc = [
53
- "ansys-sphinx-theme==1.7.2",
53
+ "ansys-sphinx-theme==1.9.0",
54
54
  "autodoc_pydantic==2.2.0",
55
55
  "numpydoc==1.10.0",
56
56
  "Sphinx==8.1.3",
@@ -58,7 +58,7 @@ doc = [
58
58
  "sphinx-copybutton==0.5.2",
59
59
  "sphinx_design==0.6.1",
60
60
  "sphinx-jinja==2.0.2",
61
- "sphinx-gallery==0.20.0",
61
+ "sphinx-gallery==0.21.0",
62
62
  ]
63
63
 
64
64
  example = [
@@ -66,11 +66,11 @@ example = [
66
66
  ]
67
67
 
68
68
  build = [
69
- "build==1.4.2",
70
- "twine==6.2.0",
69
+ "build==1.5.1",
70
+ "twine==7.0.0",
71
71
  "wheel",
72
- "datamodel-code-generator==0.55.0",
73
- "pre-commit==4.5.1",
72
+ "datamodel-code-generator==0.71.0",
73
+ "pre-commit==4.6.1",
74
74
  "importlib_metadata>=7.0",
75
75
  ]
76
76
 
@@ -33,6 +33,7 @@ import time
33
33
  import traceback
34
34
 
35
35
  import backoff
36
+ from httpx import TimeoutException
36
37
 
37
38
  from ..client import Client
38
39
  from ..exceptions import TimeoutError
@@ -140,7 +141,7 @@ class DataTransferApi:
140
141
  ----------
141
142
  operations: List[StoragePath]
142
143
  """
143
- return self._exec_operation_req("list", operations)
144
+ return self._exec_operation_req("list", operations, params={"mode": "extended"})
144
145
 
145
146
  def mkdir(self, operations: builtins.list[StoragePath]):
146
147
  """Create a directory.
@@ -180,11 +181,14 @@ class DataTransferApi:
180
181
 
181
182
  @retry()
182
183
  def _exec_operation_req(
183
- self, storage_operation: str, operations: builtins.list[StoragePath] | builtins.list[SrcDst]
184
+ self,
185
+ storage_operation: str,
186
+ operations: builtins.list[StoragePath] | builtins.list[SrcDst],
187
+ params: dict | None = None,
184
188
  ):
185
189
  url = f"/storage:{storage_operation}"
186
190
  payload = {"operations": [operation.model_dump(mode=self.dump_mode) for operation in operations]}
187
- resp = self.client.session.post(url, json=payload)
191
+ resp = self.client.session.post(url, json=payload, params=params)
188
192
  json = resp.json()
189
193
  r = OperationIdResponse(**json)
190
194
  return r
@@ -194,7 +198,9 @@ class DataTransferApi:
194
198
  params = {"ids": ids}
195
199
  if expand:
196
200
  params["expand"] = "true"
197
- resp = self.client.session.get(url, params=params, timeout=1)
201
+ # We need to timeout fairly quickly here, since the call is expected to be made and return very quickly.
202
+ # If its not, we want to know when its not working properly with some timeout messages.
203
+ resp = self.client.session.get(url, params=params, timeout=2)
198
204
  json = resp.json()
199
205
  return OperationsResponse(**json).operations
200
206
 
@@ -281,12 +287,14 @@ class DataTransferApi:
281
287
  json = resp.json()
282
288
  return OperationIdResponse(**json)
283
289
 
290
+ # Short operations need a short time, but some larger operations will be spammed
291
+ # by too many calls over their lifetime of minutes, so work up to at least 5 seconds by default.
284
292
  def wait_for(
285
293
  self,
286
294
  operation_ids: builtins.list[str | Operation | OperationIdResponse],
287
295
  timeout: float | None = None,
288
296
  interval: float = 0.1,
289
- cap: float = 2.0,
297
+ cap: float = 5.0,
290
298
  raise_on_error: bool = False,
291
299
  handler: Callable[[builtins.list[Operation]], None] = None,
292
300
  ):
@@ -330,6 +338,8 @@ class DataTransferApi:
330
338
  if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
331
339
  log.debug("All operations have completed.")
332
340
  break
341
+ except (TimeoutException, TimeoutError):
342
+ log.debug("Operations status call timed out, retrying...")
333
343
  except Exception as e:
334
344
  log.debug(f"Error getting operations: {e}")
335
345
  if raise_on_error:
@@ -35,6 +35,7 @@ import time
35
35
  import traceback
36
36
 
37
37
  import backoff
38
+ from httpx import TimeoutException
38
39
  import humanize as hz
39
40
 
40
41
  from ..client import AsyncClient
@@ -150,7 +151,7 @@ class AsyncDataTransferApi:
150
151
  params = {"ids": ids}
151
152
  if expand:
152
153
  params["expand"] = "true"
153
- resp = await self.client.session.get(url, params=params)
154
+ resp = await self.client.session.get(url, params=params, timeout=2)
154
155
  json = resp.json()
155
156
  return OperationsResponse(**json).operations
156
157
 
@@ -211,7 +212,7 @@ class AsyncDataTransferApi:
211
212
  operation_ids: builtins.list[str | Operation],
212
213
  timeout: float | None = None,
213
214
  interval: float = 0.1,
214
- cap: float = 2.0,
215
+ cap: float = 5.0,
215
216
  raise_on_error: bool = False,
216
217
  handler: Callable[[builtins.list[Operation]], Awaitable[None]] = None,
217
218
  ):
@@ -256,6 +257,8 @@ class AsyncDataTransferApi:
256
257
 
257
258
  if all(op.state in [OperationState.Succeeded, OperationState.Failed] for op in ops):
258
259
  break
260
+ except (TimeoutException, TimeoutError):
261
+ log.debug("Operations status call timed out, retrying...")
259
262
  except Exception as e:
260
263
  log.debug(f"Error getting operations: {e}")
261
264
  if raise_on_error:
@@ -83,7 +83,11 @@ class WaitHandler:
83
83
  msg = f"Data transfer {op_type} '{op.description}'({op.id}) {'finished. ' if op_done else 'is in progress. '}"
84
84
 
85
85
  try:
86
- start = op.started_at
86
+ if op.state == OperationState.Queued:
87
+ start = op.queued_at
88
+ else:
89
+ start = op.started_at
90
+
87
91
  if op_done:
88
92
  end = op.ended_at
89
93
  else:
@@ -109,29 +109,37 @@ def default_log_message(debug: bool, data: dict[str, any]):
109
109
  data : dict
110
110
  Data to log.
111
111
  """
112
- # log.warning(f"Worker: {d}")
112
+ # log.warning(f"Worker: {data}")
113
113
 
114
114
  level = data.pop("level", "info")
115
115
  data.pop("time", None)
116
116
  if not debug:
117
117
  data.pop("caller", None)
118
118
  data.pop("mode", None)
119
- msg = data.pop("message", None)
119
+ source = data.pop("source", None)
120
+ source_str = f"{source.get('file', '')}:{source.get('line', '')}" if source else ""
121
+ msg = data.pop("msg", None)
120
122
 
121
123
  if msg is None:
122
124
  return
123
125
 
124
- msg = msg.capitalize()
125
- level_no = level_map.get(level, logging.INFO)
126
+ # msg = msg.capitalize()
127
+ level_no = level_map.get(level.lower() if isinstance(level, str) else level, logging.INFO)
126
128
  other = ""
127
129
  for k, v in data.items():
128
130
  formatted_value = f'"{v}"' if isinstance(v, str) and " " in v else v
129
131
  other += f"{k}={formatted_value} "
130
132
  other = other.strip()
133
+
134
+ full_msg = "File Transfer"
135
+ if source_str and debug:
136
+ full_msg += f" ({source_str})"
137
+ full_msg = f"{full_msg}: {msg}"
131
138
  if other:
132
- msg += f" {other}"
133
- msg = msg.encode("ascii", errors="ignore").decode().strip()
134
- log.log(level_no, f"File Transfer: {msg}")
139
+ full_msg += f" {other}"
140
+
141
+ full_msg = full_msg.encode("ascii", errors="ignore").decode().strip()
142
+ log.log(level_no, full_msg)
135
143
 
136
144
 
137
145
  class BinaryConfig:
@@ -241,9 +249,9 @@ class BinaryConfig:
241
249
  def token(self, value):
242
250
  """Set token."""
243
251
  if self.debug:
244
- log.debug(
245
- f"Setting token to ...{value[-10:]}, old token: {f'...{self._token[-10:]}' if self._token else 'none'}"
246
- )
252
+ new = f"***{value[-10:]}" if value else "none"
253
+ old = f"***{self._token[-10:]}" if self._token else "none"
254
+ log.debug(f"Setting token to {new}, old token: {old}")
247
255
  self._token = value
248
256
  if self._on_token_update is not None:
249
257
  self._on_token_update()
@@ -45,7 +45,7 @@ import urllib3
45
45
 
46
46
  from ansys.hps.data_transfer.client.binary import Binary, BinaryConfig
47
47
  from ansys.hps.data_transfer.client.exceptions import BinaryError, async_raise_for_status, raise_for_status
48
- from ansys.hps.data_transfer.client.token import prepare_token
48
+ from ansys.hps.data_transfer.client.token import prepare_token, token_is_api_key
49
49
 
50
50
  urllib3.disable_warnings()
51
51
 
@@ -561,6 +561,9 @@ class ClientBase:
561
561
  Automatically refreshes the access token and
562
562
  re-sends the request in case of an unauthorized error.
563
563
  """
564
+ if self._bin_config.auth_type in ["api-key"]:
565
+ return
566
+
564
567
  log.debug(f"response status: {response.status_code} for {response.request.method} {response.url}")
565
568
  if response.status_code == 401 and self._unauthorized_num_retry < self._unauthorized_max_retry:
566
569
  log.info("401 authorization error: Trying to get a new access token.")
@@ -589,6 +592,9 @@ class ClientBase:
589
592
  Automatically refreshes the access token and
590
593
  re-sends the request in case of an unauthorized error.
591
594
  """
595
+ if self._bin_config.auth_type in ["api-key"]:
596
+ return
597
+
592
598
  log.debug(f"response status: {response.status_code} for {response.request.method} {response.url}")
593
599
  if response.status_code == 401 and self._unauthorized_num_retry < self._unauthorized_max_retry:
594
600
  log.info("401 authorization error: Trying to get a new access token.")
@@ -617,9 +623,14 @@ class ClientBase:
617
623
 
618
624
  if self.has("auth_types.api_key"):
619
625
  self._bin_config.auth_type = "api-key"
620
- self._api_key = "".join(
621
- random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(128)
622
- )
626
+ if self._bin_config.token is not None and token_is_api_key(self._bin_config.token):
627
+ log.debug("Using API key embedded in auth token")
628
+ self._api_key = self._bin_config.token[len("ApiKey ") :]
629
+ else:
630
+ log.debug("Generating random API key")
631
+ self._api_key = "".join(
632
+ random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(128)
633
+ )
623
634
  env = {
624
635
  api_key_header_env: self._api_key_header,
625
636
  api_key_value_env: self._api_key,
@@ -128,6 +128,40 @@ class CompatUploadResponseBody(BaseModel):
128
128
  checksum: str | None = None
129
129
 
130
130
 
131
+ class Format(Enum):
132
+ Tar_gz = "tar.gz"
133
+ Zip = "zip"
134
+
135
+
136
+ class CreateArchiveBody(BaseModel):
137
+ model_config = ConfigDict(
138
+ extra="allow",
139
+ )
140
+ dst: str | None = Field(
141
+ default=None,
142
+ description="Destination path for the archive file in storage",
143
+ examples=["archives/myproject.zip"],
144
+ )
145
+ format: Format | None = Field(
146
+ default=None,
147
+ description="Archive format; auto-detected from the dst file extension if omitted",
148
+ )
149
+ include_custom_metadata: bool | None = Field(
150
+ default=False,
151
+ description="Include custom metadata in the archive; if true, metadata is stored in a separate file inside the archive",
152
+ )
153
+ paths: list[str] | None = Field(
154
+ default=None,
155
+ description="Paths of files to include in the archive relative to src folder",
156
+ )
157
+ remote: str | None = Field(default="any", description="Remote storage name")
158
+ src: str | None = Field(
159
+ default=None,
160
+ description="Source folder path to archive",
161
+ examples=["projects/myproject"],
162
+ )
163
+
164
+
131
165
  class DataAssignment(BaseModel):
132
166
  model_config = ConfigDict(
133
167
  extra="allow",
@@ -194,6 +228,27 @@ class ErrorModel(BaseModel):
194
228
  )
195
229
 
196
230
 
231
+ class ExtractBody(BaseModel):
232
+ model_config = ConfigDict(
233
+ extra="allow",
234
+ )
235
+ archive_path: str | None = Field(
236
+ default=None,
237
+ description="Path of the archive file in storage",
238
+ examples=["archives/project.zip"],
239
+ )
240
+ destination: str | None = Field(
241
+ default=None,
242
+ description="Destination folder path for extracted files",
243
+ examples=["extracted/project"],
244
+ )
245
+ format: Format | None = Field(
246
+ default=None,
247
+ description="Archive format; auto-detected from the file extension if omitted",
248
+ )
249
+ remote: str | None = Field(default="any", description="Remote storage name")
250
+
251
+
197
252
  class Features(BaseModel):
198
253
  model_config = ConfigDict(
199
254
  extra="allow",
@@ -346,8 +401,9 @@ class WorkerTokenResponseBody(BaseModel):
346
401
  model_config = ConfigDict(
347
402
  extra="allow",
348
403
  )
404
+ access_token: str | None = None
349
405
  expires_at: AwareDatetime | None = None
350
- token: str | None = None
406
+ token_type: str | None = None
351
407
 
352
408
 
353
409
  class ResourceType(Enum):
@@ -366,6 +422,11 @@ class SubjectType(Enum):
366
422
  Any = "any"
367
423
 
368
424
 
425
+ class ListMode(Enum):
426
+ Basic = "basic"
427
+ Extended = "extended"
428
+
429
+
369
430
  class OperationState(Enum):
370
431
  Unknown = "unknown"
371
432
  Queued = "queued"
@@ -412,7 +473,6 @@ class Operation(BaseModel):
412
473
  error_detail: DetailedError | None = None
413
474
  id: str | None = None
414
475
  info: dict[str, Any] | None = None
415
- labels: list[str] | None = None
416
476
  max_retries: int | None = None
417
477
  messages: list[str] | None = None
418
478
  progress: float | None = None
@@ -423,6 +483,7 @@ class Operation(BaseModel):
423
483
  retries: int | None = None
424
484
  started_at: AwareDatetime | None = None
425
485
  state: OperationState | None = None
486
+ subject: str | None = None
426
487
  user_id: str | None = None
427
488
 
428
489
 
@@ -22,12 +22,24 @@
22
22
 
23
23
  """Provides a utility function for handling authentication tokens."""
24
24
 
25
+ API_KEY_PREFIX = "ApiKey "
26
+ BEARER_PREFIX = "Bearer "
27
+
25
28
 
26
29
  def prepare_token(token):
27
30
  """Prepare an authentication token by ensuring it is prefixed with ``Bearer``."""
28
31
  if token is None:
29
32
  return None
30
- tkn = token
31
- if not tkn.startswith("Bearer"):
32
- tkn = f"Bearer {tkn}"
33
- return tkn
33
+ if not token_is_bearer(token) and not token_is_api_key(token):
34
+ token = f"Bearer {token}"
35
+ return token
36
+
37
+
38
+ def token_is_bearer(token):
39
+ """Check whether the token is prefixed with ``Bearer``."""
40
+ return token.lower().startswith(BEARER_PREFIX.lower())
41
+
42
+
43
+ def token_is_api_key(token):
44
+ """Check whether the token is prefixed with ``ApiKey``."""
45
+ return token.lower().startswith(API_KEY_PREFIX.lower())