frequenz-client-base 0.11.0__tar.gz → 0.11.2__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.
- frequenz_client_base-0.11.2/PKG-INFO +506 -0
- frequenz_client_base-0.11.2/README.md +434 -0
- frequenz_client_base-0.11.2/RELEASE_NOTES.md +17 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/pyproject.toml +26 -26
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/retry.py +4 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/streaming.py +20 -9
- frequenz_client_base-0.11.2/src/frequenz_client_base.egg-info/PKG-INFO +506 -0
- frequenz_client_base-0.11.2/src/frequenz_client_base.egg-info/requires.txt +56 -0
- frequenz_client_base-0.11.0/PKG-INFO +0 -94
- frequenz_client_base-0.11.0/README.md +0 -22
- frequenz_client_base-0.11.0/RELEASE_NOTES.md +0 -42
- frequenz_client_base-0.11.0/src/frequenz_client_base.egg-info/PKG-INFO +0 -94
- frequenz_client_base-0.11.0/src/frequenz_client_base.egg-info/requires.txt +0 -56
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/LICENSE +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/MANIFEST.in +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/setup.cfg +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/__init__.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/authentication.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/channel.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/client.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/conftest.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/conversion.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/exception.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/py.typed +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz/client/base/signing.py +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz_client_base.egg-info/SOURCES.txt +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
- {frequenz_client_base-0.11.0 → frequenz_client_base-0.11.2}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: frequenz-client-base
|
|
3
|
+
Version: 0.11.2
|
|
4
|
+
Summary: Utilities for writing Frequenz API clients
|
|
5
|
+
Author-email: Frequenz Energy-as-a-Service GmbH <floss@frequenz.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Documentation, https://frequenz-floss.github.io/frequenz-client-base-python/
|
|
8
|
+
Project-URL: Changelog, https://github.com/frequenz-floss/frequenz-client-base-python/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/frequenz-floss/frequenz-client-base-python/issues
|
|
10
|
+
Project-URL: Repository, https://github.com/frequenz-floss/frequenz-client-base-python
|
|
11
|
+
Project-URL: Support, https://github.com/frequenz-floss/frequenz-client-base-python/discussions/categories/support
|
|
12
|
+
Keywords: frequenz,python,lib,library,client-base
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: <4,>=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: frequenz-channels<2,>=1.8.0
|
|
24
|
+
Requires-Dist: grpcio<2,>=1.59
|
|
25
|
+
Requires-Dist: protobuf<7,>=5.29.2
|
|
26
|
+
Requires-Dist: typing-extensions<5,>=4.12.0
|
|
27
|
+
Provides-Extra: dev-flake8
|
|
28
|
+
Requires-Dist: flake8==7.3.0; extra == "dev-flake8"
|
|
29
|
+
Requires-Dist: flake8-docstrings==1.7.0; extra == "dev-flake8"
|
|
30
|
+
Requires-Dist: flake8-pyproject==1.2.4; extra == "dev-flake8"
|
|
31
|
+
Requires-Dist: pydoclint==0.8.3; extra == "dev-flake8"
|
|
32
|
+
Requires-Dist: pydocstyle==6.3.0; extra == "dev-flake8"
|
|
33
|
+
Requires-Dist: frequenz-client-base; extra == "dev-flake8"
|
|
34
|
+
Provides-Extra: dev-formatting
|
|
35
|
+
Requires-Dist: black==25.12.0; extra == "dev-formatting"
|
|
36
|
+
Requires-Dist: isort==7.0.0; extra == "dev-formatting"
|
|
37
|
+
Provides-Extra: dev-mkdocs
|
|
38
|
+
Requires-Dist: black==25.12.0; extra == "dev-mkdocs"
|
|
39
|
+
Requires-Dist: Markdown==3.10; extra == "dev-mkdocs"
|
|
40
|
+
Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
|
|
41
|
+
Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
|
|
42
|
+
Requires-Dist: mkdocs-literate-nav==0.6.2; extra == "dev-mkdocs"
|
|
43
|
+
Requires-Dist: mkdocs-macros-plugin==1.5.0; extra == "dev-mkdocs"
|
|
44
|
+
Requires-Dist: mkdocs-material==9.7.1; extra == "dev-mkdocs"
|
|
45
|
+
Requires-Dist: mkdocstrings[python]==1.0.0; extra == "dev-mkdocs"
|
|
46
|
+
Requires-Dist: mkdocstrings-python==1.18.2; extra == "dev-mkdocs"
|
|
47
|
+
Requires-Dist: frequenz-repo-config[lib]==0.13.7; extra == "dev-mkdocs"
|
|
48
|
+
Requires-Dist: frequenz-client-base; extra == "dev-mkdocs"
|
|
49
|
+
Provides-Extra: dev-mypy
|
|
50
|
+
Requires-Dist: mypy==1.19.1; extra == "dev-mypy"
|
|
51
|
+
Requires-Dist: types-Markdown==3.10.0.20251106; extra == "dev-mypy"
|
|
52
|
+
Requires-Dist: types-protobuf==6.32.1.20251105; extra == "dev-mypy"
|
|
53
|
+
Requires-Dist: grpc-stubs==1.53.0.6; extra == "dev-mypy"
|
|
54
|
+
Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-mypy"
|
|
55
|
+
Provides-Extra: dev-noxfile
|
|
56
|
+
Requires-Dist: nox==2025.11.12; extra == "dev-noxfile"
|
|
57
|
+
Requires-Dist: frequenz-repo-config[lib]==0.13.7; extra == "dev-noxfile"
|
|
58
|
+
Provides-Extra: dev-pylint
|
|
59
|
+
Requires-Dist: pylint==4.0.4; extra == "dev-pylint"
|
|
60
|
+
Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-pylint"
|
|
61
|
+
Provides-Extra: dev-pytest
|
|
62
|
+
Requires-Dist: pytest==8.4.2; extra == "dev-pytest"
|
|
63
|
+
Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.7; extra == "dev-pytest"
|
|
64
|
+
Requires-Dist: pytest-mock==3.15.1; extra == "dev-pytest"
|
|
65
|
+
Requires-Dist: pytest-asyncio==1.3.0; extra == "dev-pytest"
|
|
66
|
+
Requires-Dist: async-solipsism==0.8; extra == "dev-pytest"
|
|
67
|
+
Requires-Dist: hypothesis==6.148.7; extra == "dev-pytest"
|
|
68
|
+
Requires-Dist: frequenz-client-base; extra == "dev-pytest"
|
|
69
|
+
Provides-Extra: dev
|
|
70
|
+
Requires-Dist: frequenz-client-base[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]; extra == "dev"
|
|
71
|
+
Dynamic: license-file
|
|
72
|
+
|
|
73
|
+
# Frequenz Client Base Library
|
|
74
|
+
|
|
75
|
+
[](https://github.com/frequenz-floss/frequenz-client-base-python/actions/workflows/ci.yaml)
|
|
76
|
+
[](https://pypi.org/project/frequenz-client-base/)
|
|
77
|
+
[](https://frequenz-floss.github.io/frequenz-client-base-python/)
|
|
78
|
+
|
|
79
|
+
## Introduction
|
|
80
|
+
|
|
81
|
+
This library provides base utilities and classes for creating Frequenz API
|
|
82
|
+
clients. It simplifies the process of creating clients that can connect to the
|
|
83
|
+
Frequenz platform, handle authentication, and manage communication channels.
|
|
84
|
+
|
|
85
|
+
## Supported Platforms
|
|
86
|
+
|
|
87
|
+
The following platforms are officially supported (tested):
|
|
88
|
+
|
|
89
|
+
- **Python:** 3.11
|
|
90
|
+
- **Operating System:** Ubuntu Linux 24.04
|
|
91
|
+
- **Architectures:** amd64, arm64
|
|
92
|
+
|
|
93
|
+
> [!NOTE]
|
|
94
|
+
> Newer Python versions and other operating systems and architectures might
|
|
95
|
+
> work too, but they are not automatically tested, so we cannot guarantee it.
|
|
96
|
+
|
|
97
|
+
## Quick Start
|
|
98
|
+
|
|
99
|
+
### Installing
|
|
100
|
+
|
|
101
|
+
Assuming a [supported](#supported-platforms) working Python environment:
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
python3 -m pip install frequenz-client-base
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### gRPC URLs
|
|
108
|
+
|
|
109
|
+
The `BaseApiClient` and its subclasses use a gRPC URL to specify the connection
|
|
110
|
+
parameters. The URL must have the following format:
|
|
111
|
+
|
|
112
|
+
`grpc://hostname[:port][?param=value&...]`
|
|
113
|
+
|
|
114
|
+
A few things to consider about URI components:
|
|
115
|
+
|
|
116
|
+
- If any other components are present in the URI, a `ValueError` is raised.
|
|
117
|
+
- If the port is omitted, a default port must be configured in the client,
|
|
118
|
+
otherwise a `ValueError` is raised.
|
|
119
|
+
- If a query parameter is passed many times, the last value is used.
|
|
120
|
+
- Boolean query parameters can be specified with the following values
|
|
121
|
+
(case-insensitive): `true`, `1`, `on`, `false`, `0`, `off`.
|
|
122
|
+
|
|
123
|
+
Supported query parameters:
|
|
124
|
+
|
|
125
|
+
- `ssl` (bool): Enable or disable SSL. Defaults to `True`.
|
|
126
|
+
- `ssl_root_certificates_path` (str): Path to the root certificates file. Only
|
|
127
|
+
valid if SSL is enabled. Will raise a `ValueError` if the file cannot be read.
|
|
128
|
+
- `ssl_private_key_path` (str): Path to the private key file. Only valid if SSL
|
|
129
|
+
is enabled. Will raise a `ValueError` if the file cannot be read.
|
|
130
|
+
- `ssl_certificate_chain_path` (str): Path to the certificate chain file. Only
|
|
131
|
+
valid if SSL is enabled. Will raise a `ValueError` if the file cannot be read.
|
|
132
|
+
- `keep_alive` (bool): Enable or disable HTTP2 keep-alive. Defaults to `True`.
|
|
133
|
+
- `keep_alive_interval_s` (float): The interval between HTTP2 pings in seconds.
|
|
134
|
+
Defaults to 60.
|
|
135
|
+
- `keep_alive_timeout_s` (float): The time to wait for a HTTP2 keep-alive
|
|
136
|
+
response in seconds. Defaults to 20.
|
|
137
|
+
|
|
138
|
+
For example:
|
|
139
|
+
|
|
140
|
+
- `grpc://localhost:50051?ssl=off`: Connect to `localhost:50051` without SSL.
|
|
141
|
+
- `grpc://api.frequenz.io:443?keep_alive_interval_s=30`: Connect to
|
|
142
|
+
`api.frequenz.io:443` with SSL and a keep-alive interval of 30 seconds.
|
|
143
|
+
- `grpc://localhost:8443?ssl_root_certificates_path=/path/to/ca.pem&ssl_private_key_path=/path/to/key.pem&ssl_certificate_chain_path=/path/to/cert.pem`:
|
|
144
|
+
Connect to `localhost:8443` with SSL and custom certificates.
|
|
145
|
+
|
|
146
|
+
### Examples
|
|
147
|
+
|
|
148
|
+
Examples assume you have generated Python code from the `helloworld.proto` file
|
|
149
|
+
from the `grpc` examples, which you can find
|
|
150
|
+
[here](https://raw.githubusercontent.com/grpc/grpc/89341001058172bd25ff1392dd7653b48d39dc62/examples/protos/helloworld.proto).
|
|
151
|
+
|
|
152
|
+
We will not explain in detail on how to generate Python files from protobuf
|
|
153
|
+
files, but this should be able to get you started:
|
|
154
|
+
|
|
155
|
+
```sh
|
|
156
|
+
mkdir example
|
|
157
|
+
cd example
|
|
158
|
+
python3 -m venv .venv
|
|
159
|
+
. .venv/bin/activate
|
|
160
|
+
curl -sO https://raw.githubusercontent.com/grpc/grpc/89341001058172bd25ff1392dd7653b48d39dc62/examples/protos/helloworld.proto
|
|
161
|
+
python3 -m pip install grpcio-tools mypy-protobuf
|
|
162
|
+
python3 -m grpc_tools.protoc -I. --python_out=. --mypy_out=. --grpc_python_out=. --mypy_grpc_out=. helloworld.proto
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
This will generate `helloworld_pb2.py`, `helloworld_pb2.pyi`, and `helloworld_pb2_grpc.py`.
|
|
166
|
+
|
|
167
|
+
#### Creating a Client
|
|
168
|
+
|
|
169
|
+
This example shows how to create a client by subclassing `BaseApiClient`.
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from __future__ import annotations
|
|
173
|
+
|
|
174
|
+
import asyncio
|
|
175
|
+
|
|
176
|
+
from frequenz.client.base.client import BaseApiClient, call_stub_method
|
|
177
|
+
from frequenz.client.base.exception import ClientNotConnected
|
|
178
|
+
|
|
179
|
+
# The following imports are from the generated files
|
|
180
|
+
import helloworld_pb2
|
|
181
|
+
import helloworld_pb2_grpc
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class GreeterApiClient(BaseApiClient[helloworld_pb2_grpc.GreeterStub]):
|
|
185
|
+
"""A client for the Greeter service."""
|
|
186
|
+
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
server_url: str,
|
|
190
|
+
*,
|
|
191
|
+
connect: bool = True,
|
|
192
|
+
) -> None:
|
|
193
|
+
"""Create a new Greeter client.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
server_url: The URL of the Greeter service.
|
|
197
|
+
connect: Whether to connect to the server immediately.
|
|
198
|
+
"""
|
|
199
|
+
super().__init__(
|
|
200
|
+
server_url,
|
|
201
|
+
helloworld_pb2_grpc.GreeterStub,
|
|
202
|
+
connect=connect,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def stub(self) -> helloworld_pb2_grpc.GreeterAsyncStub:
|
|
207
|
+
"""The gRPC stub for the API.
|
|
208
|
+
|
|
209
|
+
Raises:
|
|
210
|
+
ClientNotConnected: if the client is not connected.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
The gRPC stub.
|
|
214
|
+
"""
|
|
215
|
+
if self._stub is None:
|
|
216
|
+
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
217
|
+
# This type: ignore is needed because we need to cast the sync stub to
|
|
218
|
+
# the async stub, but we can't use cast because the async stub doesn't
|
|
219
|
+
# actually exists to the eyes of the interpreter, it only exists for the
|
|
220
|
+
# type-checker, so it can only be used for type hints.
|
|
221
|
+
return self._stub # type: ignore
|
|
222
|
+
|
|
223
|
+
async def say_hello(self, name: str) -> str:
|
|
224
|
+
"""Send a greeting to the server.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
name: The name to greet.
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
The greeting message from the server.
|
|
231
|
+
"""
|
|
232
|
+
response = await call_stub_method(
|
|
233
|
+
self,
|
|
234
|
+
lambda: self.stub.SayHello(
|
|
235
|
+
helloworld_pb2.HelloRequest(name=name), timeout=5
|
|
236
|
+
),
|
|
237
|
+
method_name="SayHello",
|
|
238
|
+
)
|
|
239
|
+
return response.message
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
async def main() -> None:
|
|
243
|
+
"""Create a client and connect to the server."""
|
|
244
|
+
async with GreeterApiClient(server_url="grpc://localhost:50051?ssl=off") as client:
|
|
245
|
+
print(await client.say_hello("Frequenz"))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
if __name__ == "__main__":
|
|
249
|
+
asyncio.run(main())
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
> [!NOTE]
|
|
253
|
+
> * We need to create a `stub` property that returns the async stub because the
|
|
254
|
+
> regular stub interface is dynamic and supports both sync and async stubs, the
|
|
255
|
+
> typing information is not correct. The `GreeterAsyncStub` is defined in the
|
|
256
|
+
> generated `.pyi` file, so the interpreter does not know about it, so we need
|
|
257
|
+
> to use a `type: ignore`.
|
|
258
|
+
> * We use the `call_stub_method` utility function to call the stub method, so gRPC
|
|
259
|
+
> errors are converted automatically to the more idiomatic
|
|
260
|
+
> `frequenz.client.base.exception.ApiClientError` exceptions.
|
|
261
|
+
|
|
262
|
+
If you want to test it, you can use the [example Python
|
|
263
|
+
server](https://github.com/grpc/grpc/blob/89341001058172bd25ff1392dd7653b48d39dc62/examples/python/helloworld/async_greeter_server.py):
|
|
264
|
+
|
|
265
|
+
```console
|
|
266
|
+
$ curl -sO https://raw.githubusercontent.com/grpc/grpc/89341001058172bd25ff1392dd7653b48d39dc62/examples/python/helloworld/async_greeter_server.py
|
|
267
|
+
$ python async_greeter_server.py
|
|
268
|
+
INFO:root:Starting server on [::]:50051
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Running the client:
|
|
272
|
+
|
|
273
|
+
```console
|
|
274
|
+
$ python3 client.py
|
|
275
|
+
Hello, Frequenz!
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
#### Streaming
|
|
279
|
+
|
|
280
|
+
This example shows how to use the `GrpcStreamBroadcaster` to handle streaming RPCs.
|
|
281
|
+
|
|
282
|
+
For this, we will use the `hellostreamingworld.proto` file from the `grpc`
|
|
283
|
+
examples. You can get it and generate the Python code with:
|
|
284
|
+
|
|
285
|
+
```sh
|
|
286
|
+
curl -sO https://raw.githubusercontent.com/grpc/grpc/89341001058172bd25ff1392dd7653b48d39dc62/examples/protos/hellostreamingworld.proto
|
|
287
|
+
python3 -m grpc_tools.protoc -I. --python_out=. --mypy_out=. --grpc_python_out=. --mypy_grpc_out=. hellostreamingworld.proto
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
This will generate `hellostreamingworld_pb2.py`, `hellostreamingworld_pb2.pyi`,
|
|
291
|
+
`hellostreamingworld_pb2_grpc.py` and `hellostreamingworld_pb2_grpc.pyi`.
|
|
292
|
+
|
|
293
|
+
The following client uses the `GrpcStreamBroadcaster` to automatically manage
|
|
294
|
+
the stream and broadcast messages to multiple receivers. It also shows how to
|
|
295
|
+
reuse the broadcaster for requests with the same `name`.
|
|
296
|
+
|
|
297
|
+
> [!NOTE]
|
|
298
|
+
> You'll need to install the `frequenz-channels` package to use the
|
|
299
|
+
> `Receiver` class:
|
|
300
|
+
>
|
|
301
|
+
> ```sh
|
|
302
|
+
> python3 -m pip install frequenz-channels
|
|
303
|
+
> ```
|
|
304
|
+
|
|
305
|
+
```python
|
|
306
|
+
from __future__ import annotations
|
|
307
|
+
|
|
308
|
+
import asyncio
|
|
309
|
+
|
|
310
|
+
from frequenz.channels import Receiver, merge
|
|
311
|
+
from frequenz.client.base.streaming import GrpcStreamBroadcaster
|
|
312
|
+
from frequenz.client.base.client import BaseApiClient
|
|
313
|
+
from frequenz.client.base.exception import ClientNotConnected
|
|
314
|
+
|
|
315
|
+
# The following imports are from the generated files
|
|
316
|
+
import hellostreamingworld_pb2 as hsw_pb2
|
|
317
|
+
import hellostreamingworld_pb2_grpc as hsw_pb2_grpc
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class StreamingGreeterApiClient(BaseApiClient[hsw_pb2_grpc.MultiGreeterStub]):
|
|
321
|
+
"""A client for the MultiGreeter service."""
|
|
322
|
+
|
|
323
|
+
def __init__(
|
|
324
|
+
self,
|
|
325
|
+
server_url: str,
|
|
326
|
+
*,
|
|
327
|
+
connect: bool = True,
|
|
328
|
+
) -> None:
|
|
329
|
+
"""Create a new StreamingGreeter client.
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
server_url: The URL of the Greeter service.
|
|
333
|
+
connect: Whether to connect to the server immediately.
|
|
334
|
+
"""
|
|
335
|
+
super().__init__(
|
|
336
|
+
server_url,
|
|
337
|
+
hsw_pb2_grpc.MultiGreeterStub,
|
|
338
|
+
connect=connect,
|
|
339
|
+
)
|
|
340
|
+
self._stream_broadcasters: dict[
|
|
341
|
+
str, GrpcStreamBroadcaster[hsw_pb2.HelloReply, str]
|
|
342
|
+
] = {}
|
|
343
|
+
|
|
344
|
+
@property
|
|
345
|
+
def stub(self) -> hsw_pb2_grpc.MultiGreeterAsyncStub:
|
|
346
|
+
"""The gRPC stub for the API.
|
|
347
|
+
|
|
348
|
+
Raises:
|
|
349
|
+
ClientNotConnected: if the client is not connected.
|
|
350
|
+
|
|
351
|
+
Returns:
|
|
352
|
+
The gRPC stub.
|
|
353
|
+
"""
|
|
354
|
+
if self._stub is None:
|
|
355
|
+
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
356
|
+
# This type: ignore is needed because we need to cast the sync stub to
|
|
357
|
+
# the async stub, but we can't use cast because the async stub doesn't
|
|
358
|
+
# actually exists to the eyes of the interpreter, it only exists for the
|
|
359
|
+
# type-checker, so it can only be used for type hints.
|
|
360
|
+
return self._stub # type: ignore
|
|
361
|
+
|
|
362
|
+
def say_hello_stream(self, name: str, *, buffer_size: int = 50) -> Receiver[str]:
|
|
363
|
+
"""Stream greetings from the server.
|
|
364
|
+
|
|
365
|
+
This method reuses the underlying stream if called multiple times with the
|
|
366
|
+
same name.
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
name: The name to greet.
|
|
370
|
+
buffer_size: The size of the receiver buffer.
|
|
371
|
+
|
|
372
|
+
Returns:
|
|
373
|
+
A receiver that will receive the greeting messages.
|
|
374
|
+
"""
|
|
375
|
+
broadcaster = self._stream_broadcasters.get(name)
|
|
376
|
+
if broadcaster is None:
|
|
377
|
+
client_id = hex(id(self))[2:]
|
|
378
|
+
stream_name = f"greeter-client-{client_id}-say-hello-stream-{name}"
|
|
379
|
+
broadcaster = GrpcStreamBroadcaster(
|
|
380
|
+
stream_name,
|
|
381
|
+
lambda: self.stub.sayHello(
|
|
382
|
+
# We hardcode the number of greetings to 10,000 for this
|
|
383
|
+
# example, just to simulate a continuous stream.
|
|
384
|
+
hsw_pb2.HelloRequest(name=name, num_greetings=str(10_000))
|
|
385
|
+
),
|
|
386
|
+
lambda reply: reply.message,
|
|
387
|
+
)
|
|
388
|
+
self._stream_broadcasters[name] = broadcaster
|
|
389
|
+
return broadcaster.new_receiver(maxsize=buffer_size)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
async def main() -> None:
|
|
393
|
+
"""Create a client and stream greetings."""
|
|
394
|
+
async with StreamingGreeterApiClient(
|
|
395
|
+
server_url="grpc://localhost:50051?ssl=off"
|
|
396
|
+
) as client:
|
|
397
|
+
# Create two receivers for the same stream
|
|
398
|
+
receiver1 = client.say_hello_stream("Frequenz")
|
|
399
|
+
receiver2 = client.say_hello_stream("Frequenz") # This will reuse the stream
|
|
400
|
+
|
|
401
|
+
# Create a receiver for a different stream
|
|
402
|
+
receiver3 = client.say_hello_stream("world")
|
|
403
|
+
|
|
404
|
+
async def print_greetings(name: str, receiver: Receiver[str]) -> None:
|
|
405
|
+
"""Print greetings from a receiver."""
|
|
406
|
+
async for message in receiver:
|
|
407
|
+
print(f"{name}: {message}")
|
|
408
|
+
print(f"{name}: Stream finished.")
|
|
409
|
+
|
|
410
|
+
i = 0
|
|
411
|
+
async for msg in merge(receiver1, receiver2, receiver3):
|
|
412
|
+
print(f"Received message {i}: {msg}")
|
|
413
|
+
i += 1
|
|
414
|
+
if i >= 10:
|
|
415
|
+
print("Stopping after 10 messages.")
|
|
416
|
+
break
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
if __name__ == "__main__":
|
|
420
|
+
asyncio.run(main())
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
If you want to test it, you can use the [example Python
|
|
424
|
+
server](https://github.com/grpc/grpc/blob/89341001058172bd25ff1392dd7653b48d39dc62/examples/python/hellostreamingworld/async_greeter_server.py):
|
|
425
|
+
|
|
426
|
+
```console
|
|
427
|
+
$ curl -sO https://raw.githubusercontent.com/grpc/grpc/89341001058172bd25ff1392dd7653b48d39dc62/examples/python/hellostreamingworld/async_greeter_server.py
|
|
428
|
+
$ python async_greeter_server.py
|
|
429
|
+
INFO:root:Starting server on [::]:50051
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Running the client:
|
|
433
|
+
|
|
434
|
+
```console
|
|
435
|
+
$ python3 streaming_client.py
|
|
436
|
+
Received message 0: Hello number 0, Frequenz!
|
|
437
|
+
Received message 1: Hello number 0, Frequenz!
|
|
438
|
+
Received message 2: Hello number 1, Frequenz!
|
|
439
|
+
Received message 3: Hello number 1, Frequenz!
|
|
440
|
+
Received message 4: Hello number 2, Frequenz!
|
|
441
|
+
Received message 5: Hello number 0, world!
|
|
442
|
+
Received message 6: Hello number 2, Frequenz!
|
|
443
|
+
Received message 7: Hello number 1, world!
|
|
444
|
+
Received message 8: Hello number 3, Frequenz!
|
|
445
|
+
Received message 9: Hello number 3, Frequenz!
|
|
446
|
+
Stopping after 10 messages.
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
#### Authorization and Signing
|
|
450
|
+
|
|
451
|
+
This library also provides utilities for handling authorization and message
|
|
452
|
+
signing. You can just pass to the `BaseApiClient` constructor an `auth_key` and
|
|
453
|
+
`sign_secret` to enable these features. The base client will handle adding
|
|
454
|
+
the necessary headers to the requests and signing the messages automatically by
|
|
455
|
+
using gRPC interceptors.
|
|
456
|
+
|
|
457
|
+
```python
|
|
458
|
+
from __future__ import annotations
|
|
459
|
+
|
|
460
|
+
import asyncio
|
|
461
|
+
|
|
462
|
+
from frequenz.client.base.client import BaseApiClient, call_stub_method
|
|
463
|
+
from frequenz.client.base.exception import ClientNotConnected
|
|
464
|
+
|
|
465
|
+
# The following imports are from the generated files
|
|
466
|
+
import helloworld_pb2
|
|
467
|
+
import helloworld_pb2_grpc
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
class GreeterApiClient(BaseApiClient[helloworld_pb2_grpc.GreeterStub]):
|
|
471
|
+
"""A client for the Greeter service."""
|
|
472
|
+
|
|
473
|
+
def __init__(
|
|
474
|
+
self,
|
|
475
|
+
server_url: str,
|
|
476
|
+
*,
|
|
477
|
+
auth_key: str | None = None,
|
|
478
|
+
sign_secret: str | None = None,
|
|
479
|
+
connect: bool = True,
|
|
480
|
+
) -> None:
|
|
481
|
+
"""Create a new Greeter client.
|
|
482
|
+
|
|
483
|
+
Args:
|
|
484
|
+
server_url: The URL of the Greeter service.
|
|
485
|
+
connect: Whether to connect to the server immediately.
|
|
486
|
+
auth_key: The authorization key to use for the client.
|
|
487
|
+
sign_secret: The secret used to sign messages sent by the client.
|
|
488
|
+
"""
|
|
489
|
+
super().__init__(
|
|
490
|
+
server_url,
|
|
491
|
+
helloworld_pb2_grpc.GreeterStub,
|
|
492
|
+
connect=connect,
|
|
493
|
+
auth_key=auth_key,
|
|
494
|
+
sign_secret=sign_secret,
|
|
495
|
+
)
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
## Documentation
|
|
499
|
+
|
|
500
|
+
For more information, please read the [documentation
|
|
501
|
+
website](https://frequenz-floss.github.io/frequenz-client-base-python/).
|
|
502
|
+
|
|
503
|
+
## Contributing
|
|
504
|
+
|
|
505
|
+
If you want to know how to build this project and contribute to it, please
|
|
506
|
+
check out the [Contributing Guide](CONTRIBUTING.md).
|