Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve BaseApiClient example #86

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions src/frequenz/client/base/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
from frequenz.client.base.streaming import GrpcStreamBroadcaster
from frequenz.channels import Receiver

# These classes are normally generated by protoc
# These classes are normally generated by protoc, please use mypy-protobuf to
# get proper type checking and the XxxAsyncStub class (only for typing)
# generated.
class ExampleRequest:
int_value: int
str_value: str
Expand All @@ -51,6 +53,9 @@ class ExampleResponse:
float_value: float

class ExampleStub:
...

class ExampleAsyncStub:
async def example_method(
self,
request: ExampleRequest # pylint: disable=unused-argument
Expand All @@ -65,10 +70,24 @@ class ExampleResponseWrapper:
def __init__(self, response: ExampleResponse):
self.transformed_value = f"{response.float_value:.2f}"

class MyApiClient(BaseApiClient[ExampleStub]):
def __init__(self, server_url: str, *, connect: bool = True):
# Change defaults as needed
DEFAULT_CHANNEL_OPTIONS = ChannelOptions()

class MyApiClient(BaseApiClient[ExampleAsyncStub]):
def __init__(
self,
server_url: str,
*,
connect: bool = True,
channel_defaults: ChannelOptions = DEFAULT_CHANNEL_OPTIONS,
) -> None:
super().__init__(
server_url, ExampleStub, connect=connect
server_url,
# We need to type ignore here because the generated normal and
# async stubs are not type-compatible with each other.
ExampleStub, # type: ignore[arg-type]
connect=connect,
channel_defaults=channel_defaults,
)
self._broadcaster = GrpcStreamBroadcaster(
"stream",
Expand Down
Loading