Skip to content

Commit c7f6341

Browse files
authored
RSDK-4756 - add Options api-key helper function (#469)
1 parent a678974 commit c7f6341

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/viam/robot/client.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,26 @@ class Options:
101101
Whether sessions are disabled
102102
"""
103103

104+
@classmethod
105+
def with_api_key(cls, api_key: str, api_key_id: str) -> Self:
106+
"""
107+
Create RobotClient.Options with an API key for credentials and default values for other arguments.
108+
109+
Args:
110+
api_key (str): your API key
111+
api_key_id (str): your API key ID. Must be a valid UUID
112+
113+
Raises:
114+
ValueError: Raised if the api_key_id is not a valid UUID
115+
116+
Returns:
117+
Self: the RobotClient.Options
118+
"""
119+
dial_opts = DialOptions.with_api_key(api_key, api_key_id)
120+
self = cls()
121+
self.dial_options = dial_opts
122+
return self
123+
104124
@classmethod
105125
async def at_address(cls, address: str, options: Options) -> Self:
106126
"""Create a robot client that is connected to the robot at the provided address.

src/viam/rpc/dial.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44
import socket
55
import ssl
66
import sys
7+
import uuid
78
import warnings
89
from dataclasses import dataclass
910
from typing import Callable, Literal, Optional, Tuple, Type, Union
11+
from typing_extensions import Self
1012

1113
from grpclib.client import Channel, Stream
1214
from grpclib.const import Cardinality
@@ -90,6 +92,28 @@ def __init__(
9092
self.max_reconnect_attempts = max_reconnect_attempts
9193
self.timeout = timeout
9294

95+
@classmethod
96+
def with_api_key(cls, api_key: str, api_key_id: str) -> Self:
97+
"""Create DialOptions with an API key for credentials and default values for other arguments.
98+
99+
Args:
100+
api_key (str): your API key
101+
api_key_id (str): your API key ID. Must be a valid UUID
102+
103+
Raises:
104+
ValueError: Raised if the api_key_id is not a valid UUID
105+
106+
Returns:
107+
Self: the DialOptions
108+
"""
109+
try:
110+
uuid.UUID(api_key_id)
111+
except ValueError:
112+
raise ValueError(f"{api_key_id} is not a valid UUID")
113+
114+
credentials = Credentials(type="api-key", payload=api_key)
115+
return cls(credentials=credentials, auth_entity=api_key_id)
116+
93117

94118
def _host_port_from_url(url) -> Tuple[Optional[str], Optional[int]]:
95119
query = "(?:.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*"

0 commit comments

Comments
 (0)