tsurara-client 0.1.0__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 (30) hide show
  1. tsurara_client-0.1.0/.gitignore +3 -0
  2. tsurara_client-0.1.0/.python-version +1 -0
  3. tsurara_client-0.1.0/LICENSE +21 -0
  4. tsurara_client-0.1.0/PKG-INFO +118 -0
  5. tsurara_client-0.1.0/README.md +106 -0
  6. tsurara_client-0.1.0/pyproject.toml +27 -0
  7. tsurara_client-0.1.0/pyrightconfig.json +8 -0
  8. tsurara_client-0.1.0/src/tsurara_client/__init__.py +111 -0
  9. tsurara_client-0.1.0/src/tsurara_client/_auth.py +109 -0
  10. tsurara_client-0.1.0/src/tsurara_client/_client.py +680 -0
  11. tsurara_client-0.1.0/src/tsurara_client/_codec.py +301 -0
  12. tsurara_client-0.1.0/src/tsurara_client/_def.py +68 -0
  13. tsurara_client-0.1.0/src/tsurara_client/_file.py +13 -0
  14. tsurara_client-0.1.0/src/tsurara_client/_info.py +40 -0
  15. tsurara_client-0.1.0/src/tsurara_client/_missing.py +24 -0
  16. tsurara_client-0.1.0/src/tsurara_client/_result.py +118 -0
  17. tsurara_client-0.1.0/src/tsurara_client/_retry.py +59 -0
  18. tsurara_client-0.1.0/src/tsurara_client/_sequences.py +116 -0
  19. tsurara_client-0.1.0/src/tsurara_client/_serialize.py +311 -0
  20. tsurara_client-0.1.0/src/tsurara_client/_unwrap.py +44 -0
  21. tsurara_client-0.1.0/src/tsurara_client/py.typed +0 -0
  22. tsurara_client-0.1.0/src/tsurara_client/support.py +12 -0
  23. tsurara_client-0.1.0/src/tsurara_client/testing.py +212 -0
  24. tsurara_client-0.1.0/tests/test_client.py +227 -0
  25. tsurara_client-0.1.0/tests/test_conformance.py +227 -0
  26. tsurara_client-0.1.0/tests/test_retry.py +116 -0
  27. tsurara_client-0.1.0/tests/test_sequences.py +116 -0
  28. tsurara_client-0.1.0/tests/test_testing.py +119 -0
  29. tsurara_client-0.1.0/tests/test_typedefs.py +175 -0
  30. tsurara_client-0.1.0/uv.lock +167 -0
@@ -0,0 +1,3 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
@@ -0,0 +1 @@
1
+ 3.11
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nazo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: tsurara-client
3
+ Version: 0.1.0
4
+ Summary: Runtime library for Python code generated by tsurara
5
+ Project-URL: Repository, https://github.com/tsurara-openapi/tsurara
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Provides-Extra: http
10
+ Requires-Dist: httpx>=0.27; extra == 'http'
11
+ Description-Content-Type: text/markdown
12
+
13
+ # tsurara-client
14
+
15
+ The runtime library for Python code generated by tsurara (`language: python`). Generated call functions pass an OperationDef to a client, which builds the request, sends it with [httpx](https://www.python-httpx.org/), and returns a result instead of raising. Values are converted with the TypeDefs the generator emits: records become the generated dataclasses and enums their `Enum` classes. It implements the runtime contract in `spec/` and passes its conformance vectors. Python 3.11 or later.
16
+
17
+ Install `tsurara-client[http]` for the client. Without the extra, the package has no dependencies, and code generated with `operations: false` uses only its types layer (`TypeDefs`, `File`, `MISSING`); the client's names are imported on first use and need httpx.
18
+
19
+ ```python
20
+ from tsurara_client import Client, HttpError, Success, unwrap
21
+
22
+ from api import get_pet # generated
23
+
24
+ with Client("https://api.example.com", headers={"Authorization": "Bearer ..."}, timeout=10) as client:
25
+ match get_pet(client, pet_id=1):
26
+ case Success(data=pet):
27
+ print(pet.name)
28
+ case HttpError(status=404):
29
+ print("no such pet")
30
+ case other:
31
+ print("failed:", other.kind)
32
+ pet = unwrap(get_pet(client, pet_id=1)) # raises ApiError on failure
33
+ ```
34
+
35
+ `AsyncClient` takes the same options, and the same generated functions return awaitables with it:
36
+
37
+ ```python
38
+ async with AsyncClient("https://api.example.com") as client:
39
+ pet = unwrap(await get_pet(client, pet_id=1))
40
+ ```
41
+
42
+ ## Results
43
+
44
+ | Class | `kind` | When |
45
+ |---|---|---|
46
+ | `Success` | `success` | A success status of the definition; `data` has its type |
47
+ | `HttpError` | `http` | An error status the definition documents; `error` has its type, `documented` is `True` |
48
+ | `UndocumentedStatus` | `http` | Any status the definition does not document, also a 2xx when other successes are documented; `documented` is `False` |
49
+ | `NetworkFailure` | `network` | Connection, DNS or TLS failures |
50
+ | `TimeoutFailure` | `timeout` | The timeout was exceeded |
51
+ | `ParseFailure` | `parse` | The body does not match the definition (Content-Type, JSON, or the type) |
52
+ | `UnexpectedFailure` | `unexpected` | A hook or converter raised, or the input cannot be sent |
53
+
54
+ Cancelling an async call raises `asyncio.CancelledError` as usual; there is no `aborted` result.
55
+
56
+ ### Streams
57
+
58
+ A success read item by item (`parseAs` `events`, `jsonLines` or `jsonSeq`) has an iterator as `data` (an async iterator with `AsyncClient`), and the response stays open while it is read:
59
+
60
+ ```python
61
+ r = stream(client)
62
+ if isinstance(r, Success):
63
+ with contextlib.closing(r.data) as events: # `aclosing` with AsyncClient
64
+ for event in events:
65
+ ...
66
+ ```
67
+
68
+ - Reading to the end or closing the iterator closes the response; an iterator dropped half-read keeps its connection until it is collected.
69
+ - `timeout` covers connecting and the response headers, not the wait for the next item.
70
+ - Invalid JSON in an item raises `ValueError` from the iteration, and a broken connection raises httpx's error, since the Result was already returned.
71
+
72
+ ## Options
73
+
74
+ | Option | Description |
75
+ |---|---|
76
+ | `headers` | Headers for every request, or a function of the request info returning them (async with `AsyncClient`) |
77
+ | `timeout` | Seconds, for each request; per call with `timeout=` |
78
+ | `http` | The `httpx.Client` / `httpx.AsyncClient` to send with: proxies, transports (retries), event hooks, tests with `httpx.MockTransport`. The client closes only the one it made |
79
+ | `on_result` | Observes every result |
80
+ | `on_undocumented_status` | Observes responses whose status the definition does not document, to notice drift between the server and the definition |
81
+ | `auth` | `auth(scheme, info)` returns the credential for a security scheme of the operation (`scheme.scheme` is its name; generated `SecuritySchemeName` lists them), or `None`. API keys go in their header, query or cookie, bearer and OAuth tokens in `Authorization: Bearer`, basic credentials (`user:password`) in `Authorization: Basic` |
82
+ | `retry` | `Retry()` retries network failures and 408, 429, 500, 502, 503 and 504 for idempotent methods, up to 2 times, honoring `Retry-After` and otherwise backing off with jitter; `timeout` covers all attempts |
83
+
84
+ Hooks never change the result; their exceptions are ignored.
85
+
86
+ ## Values
87
+
88
+ - `MISSING` marks a field absent from JSON, as opposed to `None` (`null`); only fields that are both optional and nullable use it.
89
+ - Unlisted values of open enums and open tagged unions stay as their JSON values (`Status | str`).
90
+ - Binary values are `bytes`, or `File(content, filename=..., content_type=...)` when a multipart part or body needs a name or media type. Binary responses are `bytes`.
91
+ - External types (`x-tsurara-type`) are converted by converters registered by name: `TypeDefs.with_converters({"Uuid": UuidConverter()})`.
92
+
93
+ ## Testing without a server
94
+
95
+ `tsurara_client.testing.MockRouter` is an httpx mock handler that answers from handlers routed by operation (spec/README.md, Mock transports), for `Client` and `AsyncClient`:
96
+
97
+ ```python
98
+ import httpx
99
+ from tsurara_client import Client
100
+ from tsurara_client.testing import MockResponse, MockRouter
101
+
102
+ from api.operations.get_pet import DEF as GET_PET # generated
103
+
104
+ router = MockRouter(base_path="/v1")
105
+ router.add(GET_PET, lambda req: MockResponse(200, json={"id": int(req.params["pet_id"]), "name": "Pochi"}))
106
+ client = Client("https://api.test/v1", http=httpx.Client(transport=httpx.MockTransport(router)))
107
+ # ... call generated functions, then inspect router.calls
108
+ ```
109
+
110
+ `router.route(method, path, handler)` adds a route without an OperationDef. A handler that raises, and a request no route matches, are `NetworkFailure`s; with `MockRouter(unmatched="record")`, unmatched requests are answered with 501 and kept in `router.unmatched`.
111
+
112
+ ## Development
113
+
114
+ ```sh
115
+ uv sync --project runtimes/python
116
+ uv run --directory runtimes/python pytest
117
+ node_modules/.bin/pyright -p runtimes/python
118
+ ```
@@ -0,0 +1,106 @@
1
+ # tsurara-client
2
+
3
+ The runtime library for Python code generated by tsurara (`language: python`). Generated call functions pass an OperationDef to a client, which builds the request, sends it with [httpx](https://www.python-httpx.org/), and returns a result instead of raising. Values are converted with the TypeDefs the generator emits: records become the generated dataclasses and enums their `Enum` classes. It implements the runtime contract in `spec/` and passes its conformance vectors. Python 3.11 or later.
4
+
5
+ Install `tsurara-client[http]` for the client. Without the extra, the package has no dependencies, and code generated with `operations: false` uses only its types layer (`TypeDefs`, `File`, `MISSING`); the client's names are imported on first use and need httpx.
6
+
7
+ ```python
8
+ from tsurara_client import Client, HttpError, Success, unwrap
9
+
10
+ from api import get_pet # generated
11
+
12
+ with Client("https://api.example.com", headers={"Authorization": "Bearer ..."}, timeout=10) as client:
13
+ match get_pet(client, pet_id=1):
14
+ case Success(data=pet):
15
+ print(pet.name)
16
+ case HttpError(status=404):
17
+ print("no such pet")
18
+ case other:
19
+ print("failed:", other.kind)
20
+ pet = unwrap(get_pet(client, pet_id=1)) # raises ApiError on failure
21
+ ```
22
+
23
+ `AsyncClient` takes the same options, and the same generated functions return awaitables with it:
24
+
25
+ ```python
26
+ async with AsyncClient("https://api.example.com") as client:
27
+ pet = unwrap(await get_pet(client, pet_id=1))
28
+ ```
29
+
30
+ ## Results
31
+
32
+ | Class | `kind` | When |
33
+ |---|---|---|
34
+ | `Success` | `success` | A success status of the definition; `data` has its type |
35
+ | `HttpError` | `http` | An error status the definition documents; `error` has its type, `documented` is `True` |
36
+ | `UndocumentedStatus` | `http` | Any status the definition does not document, also a 2xx when other successes are documented; `documented` is `False` |
37
+ | `NetworkFailure` | `network` | Connection, DNS or TLS failures |
38
+ | `TimeoutFailure` | `timeout` | The timeout was exceeded |
39
+ | `ParseFailure` | `parse` | The body does not match the definition (Content-Type, JSON, or the type) |
40
+ | `UnexpectedFailure` | `unexpected` | A hook or converter raised, or the input cannot be sent |
41
+
42
+ Cancelling an async call raises `asyncio.CancelledError` as usual; there is no `aborted` result.
43
+
44
+ ### Streams
45
+
46
+ A success read item by item (`parseAs` `events`, `jsonLines` or `jsonSeq`) has an iterator as `data` (an async iterator with `AsyncClient`), and the response stays open while it is read:
47
+
48
+ ```python
49
+ r = stream(client)
50
+ if isinstance(r, Success):
51
+ with contextlib.closing(r.data) as events: # `aclosing` with AsyncClient
52
+ for event in events:
53
+ ...
54
+ ```
55
+
56
+ - Reading to the end or closing the iterator closes the response; an iterator dropped half-read keeps its connection until it is collected.
57
+ - `timeout` covers connecting and the response headers, not the wait for the next item.
58
+ - Invalid JSON in an item raises `ValueError` from the iteration, and a broken connection raises httpx's error, since the Result was already returned.
59
+
60
+ ## Options
61
+
62
+ | Option | Description |
63
+ |---|---|
64
+ | `headers` | Headers for every request, or a function of the request info returning them (async with `AsyncClient`) |
65
+ | `timeout` | Seconds, for each request; per call with `timeout=` |
66
+ | `http` | The `httpx.Client` / `httpx.AsyncClient` to send with: proxies, transports (retries), event hooks, tests with `httpx.MockTransport`. The client closes only the one it made |
67
+ | `on_result` | Observes every result |
68
+ | `on_undocumented_status` | Observes responses whose status the definition does not document, to notice drift between the server and the definition |
69
+ | `auth` | `auth(scheme, info)` returns the credential for a security scheme of the operation (`scheme.scheme` is its name; generated `SecuritySchemeName` lists them), or `None`. API keys go in their header, query or cookie, bearer and OAuth tokens in `Authorization: Bearer`, basic credentials (`user:password`) in `Authorization: Basic` |
70
+ | `retry` | `Retry()` retries network failures and 408, 429, 500, 502, 503 and 504 for idempotent methods, up to 2 times, honoring `Retry-After` and otherwise backing off with jitter; `timeout` covers all attempts |
71
+
72
+ Hooks never change the result; their exceptions are ignored.
73
+
74
+ ## Values
75
+
76
+ - `MISSING` marks a field absent from JSON, as opposed to `None` (`null`); only fields that are both optional and nullable use it.
77
+ - Unlisted values of open enums and open tagged unions stay as their JSON values (`Status | str`).
78
+ - Binary values are `bytes`, or `File(content, filename=..., content_type=...)` when a multipart part or body needs a name or media type. Binary responses are `bytes`.
79
+ - External types (`x-tsurara-type`) are converted by converters registered by name: `TypeDefs.with_converters({"Uuid": UuidConverter()})`.
80
+
81
+ ## Testing without a server
82
+
83
+ `tsurara_client.testing.MockRouter` is an httpx mock handler that answers from handlers routed by operation (spec/README.md, Mock transports), for `Client` and `AsyncClient`:
84
+
85
+ ```python
86
+ import httpx
87
+ from tsurara_client import Client
88
+ from tsurara_client.testing import MockResponse, MockRouter
89
+
90
+ from api.operations.get_pet import DEF as GET_PET # generated
91
+
92
+ router = MockRouter(base_path="/v1")
93
+ router.add(GET_PET, lambda req: MockResponse(200, json={"id": int(req.params["pet_id"]), "name": "Pochi"}))
94
+ client = Client("https://api.test/v1", http=httpx.Client(transport=httpx.MockTransport(router)))
95
+ # ... call generated functions, then inspect router.calls
96
+ ```
97
+
98
+ `router.route(method, path, handler)` adds a route without an OperationDef. A handler that raises, and a request no route matches, are `NetworkFailure`s; with `MockRouter(unmatched="record")`, unmatched requests are answered with 501 and kept in `router.unmatched`.
99
+
100
+ ## Development
101
+
102
+ ```sh
103
+ uv sync --project runtimes/python
104
+ uv run --directory runtimes/python pytest
105
+ node_modules/.bin/pyright -p runtimes/python
106
+ ```
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "tsurara-client"
3
+ version = "0.1.0"
4
+ description = "Runtime library for Python code generated by tsurara"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = []
9
+
10
+ [project.optional-dependencies]
11
+ http = ["httpx>=0.27"]
12
+
13
+ [dependency-groups]
14
+ dev = ["pytest>=8", "httpx>=0.27"]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/tsurara-openapi/tsurara"
18
+
19
+ [build-system]
20
+ requires = ["hatchling==1.33.0"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/tsurara_client"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
@@ -0,0 +1,8 @@
1
+ {
2
+ "include": ["src", "tests"],
3
+ "strict": ["src"],
4
+ "venvPath": ".",
5
+ "venv": ".venv",
6
+ "pythonVersion": "3.11",
7
+ "typeCheckingMode": "standard"
8
+ }
@@ -0,0 +1,111 @@
1
+ """The runtime library for Python code generated by tsurara (design.md 18.9).
2
+
3
+ Two layers: the types layer (``TypeDefs``, ``File``, ``MISSING``, ``OperationDef``,
4
+ ``SecurityScheme``) needs nothing but the standard library; the client layer (``Client``, the
5
+ Results, ``Retry``, ``unwrap``) needs httpx, installed with the ``http`` extra
6
+ (``tsurara-client[http]``). Its names are imported on first use, so code generated with
7
+ ``operations: false`` imports this package without httpx.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from ._auth import SecurityScheme
16
+ from ._codec import ConversionError, Converter, TypeDefs
17
+ from ._def import OPERATION_DEF_VERSION, OperationDef
18
+ from ._file import File
19
+ from ._missing import MISSING, Missing
20
+
21
+ if TYPE_CHECKING:
22
+ from ._client import AsyncClient, Auth, Client, HeaderValues
23
+ from ._info import OperationInfo, RequestInfo, UndocumentedStatusInfo
24
+ from ._result import (
25
+ AnyResult,
26
+ HttpError,
27
+ NetworkFailure,
28
+ ParseFailure,
29
+ Success,
30
+ TimeoutFailure,
31
+ TransportFailure,
32
+ UndocumentedStatus,
33
+ UnexpectedFailure,
34
+ )
35
+ from ._retry import Retry, retry_after
36
+ from ._unwrap import ApiError, unwrap
37
+
38
+ __version__ = "0.1.0"
39
+
40
+ _CLIENT: dict[str, str] = {
41
+ "AsyncClient": "._client",
42
+ "Auth": "._client",
43
+ "Client": "._client",
44
+ "HeaderValues": "._client",
45
+ "OperationInfo": "._info",
46
+ "RequestInfo": "._info",
47
+ "UndocumentedStatusInfo": "._info",
48
+ "AnyResult": "._result",
49
+ "HttpError": "._result",
50
+ "NetworkFailure": "._result",
51
+ "ParseFailure": "._result",
52
+ "Success": "._result",
53
+ "TimeoutFailure": "._result",
54
+ "TransportFailure": "._result",
55
+ "UndocumentedStatus": "._result",
56
+ "UnexpectedFailure": "._result",
57
+ "Retry": "._retry",
58
+ "retry_after": "._retry",
59
+ "ApiError": "._unwrap",
60
+ "unwrap": "._unwrap",
61
+ }
62
+
63
+
64
+ def __getattr__(name: str) -> Any:
65
+ module = _CLIENT.get(name)
66
+ if module is None:
67
+ raise AttributeError(f"module 'tsurara_client' has no attribute {name!r}")
68
+ try:
69
+ value = getattr(importlib.import_module(module, __name__), name)
70
+ except ModuleNotFoundError as e:
71
+ if e.name != "httpx":
72
+ raise
73
+ raise ImportError(
74
+ f"tsurara_client.{name} needs httpx: install tsurara-client[http]",
75
+ name=name,
76
+ ) from e
77
+ globals()[name] = value
78
+ return value
79
+
80
+
81
+ __all__ = [
82
+ "MISSING",
83
+ "OPERATION_DEF_VERSION",
84
+ "AnyResult",
85
+ "ApiError",
86
+ "AsyncClient",
87
+ "Auth",
88
+ "Client",
89
+ "ConversionError",
90
+ "Converter",
91
+ "File",
92
+ "HeaderValues",
93
+ "HttpError",
94
+ "Missing",
95
+ "NetworkFailure",
96
+ "OperationDef",
97
+ "OperationInfo",
98
+ "ParseFailure",
99
+ "Retry",
100
+ "SecurityScheme",
101
+ "RequestInfo",
102
+ "Success",
103
+ "TimeoutFailure",
104
+ "TransportFailure",
105
+ "TypeDefs",
106
+ "UndocumentedStatus",
107
+ "UndocumentedStatusInfo",
108
+ "UnexpectedFailure",
109
+ "retry_after",
110
+ "unwrap",
111
+ ]
@@ -0,0 +1,109 @@
1
+ """Authentication (spec/README.md): the credentials of the first alternative of an operation's
2
+ `security` for which the auth hook gives every one, placed by scheme."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import inspect
8
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+ from urllib.parse import quote
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class SecurityScheme:
16
+ """A security scheme an operation uses, as the auth hook receives it."""
17
+
18
+ scheme: str
19
+ """The name in `components.securitySchemes`."""
20
+ type: str
21
+ """`apiKey`, `http`, `oauth2`, `openIdConnect` or `mutualTLS`."""
22
+ in_: str | None = None
23
+ """`apiKey`: `header`, `query` or `cookie`."""
24
+ name: str | None = None
25
+ """`apiKey`: the header, query or cookie name."""
26
+ http_scheme: str | None = None
27
+ """`http`: the Authorization scheme, such as `bearer` or `basic`."""
28
+ scopes: tuple[str, ...] = ()
29
+
30
+ @staticmethod
31
+ def of(use: Mapping[str, Any]) -> SecurityScheme:
32
+ return SecurityScheme(
33
+ scheme=use["scheme"],
34
+ type=use["type"],
35
+ in_=use.get("in"),
36
+ name=use.get("name"),
37
+ http_scheme=use.get("httpScheme"),
38
+ scopes=tuple(use.get("scopes", ())),
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class Credentials:
44
+ headers: dict[str, str] = field(default_factory=lambda: {})
45
+ query: list[str] = field(default_factory=lambda: [])
46
+ cookies: list[str] = field(default_factory=lambda: [])
47
+
48
+
49
+ Get = Callable[[SecurityScheme], "str | None | Awaitable[str | None]"]
50
+
51
+
52
+ def _place(out: Credentials, s: SecurityScheme, value: str) -> None:
53
+ if s.type == "apiKey":
54
+ name = s.name or s.scheme
55
+ if s.in_ == "query":
56
+ out.query.append(f"{quote(name, safe='')}={quote(value, safe='')}")
57
+ elif s.in_ == "cookie":
58
+ out.cookies.append(f"{name}={quote(value, safe='')}")
59
+ else:
60
+ out.headers[name.lower()] = value
61
+ return
62
+ http = (s.http_scheme or "bearer") if s.type == "http" else "bearer"
63
+ if http.lower() == "basic":
64
+ out.headers["authorization"] = "Basic " + base64.b64encode(value.encode()).decode()
65
+ elif http.lower() == "bearer":
66
+ out.headers["authorization"] = f"Bearer {value}"
67
+ else:
68
+ out.headers["authorization"] = f"{http} {value}"
69
+
70
+
71
+ def _alternatives(security: Sequence[Sequence[Mapping[str, Any]]] | None) -> list[list[SecurityScheme]]:
72
+ # mutualTLS is handled by the transport.
73
+ return [[SecurityScheme.of(u) for u in alt if u["type"] != "mutualTLS"] for alt in security or []]
74
+
75
+
76
+ def authenticate(security: Sequence[Sequence[Mapping[str, Any]]] | None, get: Get) -> Credentials:
77
+ out = Credentials()
78
+ for alternative in _alternatives(security):
79
+ values: list[tuple[SecurityScheme, str]] = []
80
+ for s in alternative:
81
+ value = get(s)
82
+ if inspect.isawaitable(value):
83
+ raise TypeError("an async auth function needs AsyncClient")
84
+ if value is None:
85
+ break
86
+ values.append((s, value))
87
+ if len(values) == len(alternative):
88
+ for s, v in values:
89
+ _place(out, s, v)
90
+ return out
91
+ return out
92
+
93
+
94
+ async def authenticate_async(security: Sequence[Sequence[Mapping[str, Any]]] | None, get: Get) -> Credentials:
95
+ out = Credentials()
96
+ for alternative in _alternatives(security):
97
+ values: list[tuple[SecurityScheme, str]] = []
98
+ for s in alternative:
99
+ value = get(s)
100
+ if inspect.isawaitable(value):
101
+ value = await value
102
+ if value is None:
103
+ break
104
+ values.append((s, value))
105
+ if len(values) == len(alternative):
106
+ for s, v in values:
107
+ _place(out, s, v)
108
+ return out
109
+ return out