8000 feat: add api key support (#300) · googleapis/python-vision@25fc254 · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Feb 13, 2024. It is now read-only.

Commit 25fc254

Browse files
feat: add api key support (#300)
* chore: upgrade gapic-generator-java, gax-java and gapic-generator-python PiperOrigin-RevId: 423842556 Source-Link: googleapis/googleapis@a616ca0 Source-Link: https://github.com/googleapis/googleapis-gen/commit/29b938c58c1e51d019f2ee539d55dc0a3c86a905 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjliOTM4YzU4YzFlNTFkMDE5ZjJlZTUzOWQ1NWRjMGEzYzg2YTkwNSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com>
1 parent efc526c commit 25fc254

File tree

24 files changed

+1992
-352
lines changed

24 files changed

+1992
-352
lines changed

google/cloud/vision_v1/services/image_annotator/async_client.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from collections import OrderedDict
1717
import functools
1818
import re
19-
from typing import Dict, Sequence, Tuple, Type, Union
19+
from typing import Dict, Optional, Sequence, Tuple, Type, Union
2020
import pkg_resources
2121

2222
from google.api_core.client_options import ClientOptions
@@ -113,6 +113,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
113113

114114
from_service_account_json = from_service_account_file
115115

116+
@classmethod
117+
def get_mtls_endpoint_and_cert_source(
118+
cls, client_options: Optional[ClientOptions] = None
119+
):
120+
"""Return the API endpoint and client cert source for mutual TLS.
121+
122+
The client cert source is determined in the following order:
123+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
124+
client cert source is None.
125+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
126+
default client cert source exists, use the default one; otherwise the client cert
127+
source is None.
128+
129+
The API endpoint is determined in the following order:
130+
(1) if `client_options.api_endpoint` if provided, use the provided one.
131+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
132+
default mTLS endpoint; if the environment variabel is "never", use the default API
133+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
134+
use the default API endpoint.
135+
136+
More details can be found at https://google.aip.dev/auth/4114.
137+
138+
Args:
139+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
140+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
141+
in this method.
142+
143+
Returns:
144+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
145+
client cert source to use.
146+
147+
Raises:
148+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
149+
"""
150+
return ImageAnnotatorClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
151+
116152
@property
117153
def transport(self) -> ImageAnnotatorTransport:
118154
"""Returns the transport used by the client instance.

google/cloud/vision_v1/services/image_annotator/client.py

Lines changed: 84 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
255255
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
256256
return m.groupdict() if m else {}
257257

258+
@classmethod
259+
def get_mtls_endpoint_and_cert_source(
260+
cls, client_options: Optional[client_options_lib.ClientOptions] = None
261+
):
262+
"""Return the API endpoint and client cert source for mutual TLS.
263+
264+
The client cert source is determined in the following order:
265+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
266+
client cert source is None.
267+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
268+
default client cert source exists, use the default one; otherwise the client cert
269+
source is None.
270+
271+
The API endpoint is determined in the following order:
272+
(1) if `client_options.api_endpoint` if provided, use the provided one.
273+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
274+
default mTLS endpoint; if the environment variabel is "never", use the default API
275+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
276+
use the default API endpoint.
277+
278+
More details can be found at https://google.aip.dev/auth/4114.
279+
280+
Args:
281+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
282+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
283+
in this method.
284+
285+
Returns:
286+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
287+
client cert source to use.
288+
289+
Raises:
290+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
291+
"""
292+
if client_options is None:
293+
client_options = client_options_lib.ClientOptions()
294+
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
295+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
296+
if use_client_cert not in ("true", "false"):
297+
raise ValueError(
298+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
299+
)
300+
if use_mtls_endpoint not in ("auto", "never", "always"):
301+
raise MutualTLSChannelError(
302+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
303+
)
304+
305+
# Figure out the client cert source to use.
306+
client_cert_source = None
307+
if use_client_cert == "true":
308+
if client_options.client_cert_source:
309+
client_cert_source = client_options.client_cert_source
310+
elif mtls.has_default_client_cert_source():
311+
client_cert_source = mtls.default_client_cert_source()
312+
313+
# Figure out which api endpoint to use.
314+
if client_options.api_endpoint is not None:
315+
api_endpoint = client_options.api_endpoint
316+
elif use_mtls_endpoint == "always" or (
317+
use_mtls_endpoint == "auto" and client_cert_source
318+
):
319+
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
320+
else:
321+
api_endpoint = cls.DEFAULT_ENDPOINT
322+
323+
return api_endpoint, client_cert_source
324+
258325
def __init__(
259326
self,
260327
*,
@@ -305,57 +372,22 @@ def __init__(
305372
if client_options is None:
306373
client_options = client_options_lib.ClientOptions()
307374

308-
# Create SSL credentials for mutual TLS if needed.
309-
if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
310-
"true",
311-
"false",
312-
):
313-
raise ValueError(
314-
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
315-
)
316-
use_client_cert = (
317-
os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
375+
api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
376+
client_options
318377
)
319378

320-
client_cert_source_func = None
321-
is_mtls = False
322-
if use_client_cert:
323-
if client_options.client_cert_source:
324-
is_mtls = True
325-
client_cert_source_func = client_options.client_cert_source
326-
else:
327-
is_mtls = mtls.has_default_client_cert_source()
328-
if is_mtls:
329-
client_cert_source_func = mtls.default_client_cert_source()
330-
else:
331-
client_cert_source_func = None
332-
333-
# Figure out which api endpoint to use.
334-
if client_options.api_endpoint is not None:
335-
api_endpoint = client_options.api_endpoint
336-
else:
337-
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
338-
if use_mtls_env == "never":
339-
api_endpoint = self.DEFAULT_ENDPOINT
340-
elif use_mtls_env == "always":
341-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
342-
elif use_mtls_env == "auto":
343-
if is_mtls:
344-
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
345-
else:
346-
api_endpoint = self.DEFAULT_ENDPOINT
347-
else:
348-
raise MutualTLSChannelError(
349-
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
350-
"values: never, auto, always"
351-
)
379+
api_key_value = getattr(client_options, "api_key", None)
380+
if api_key_value and credentials:
381+
raise ValueError(
382+
"client_options.api_key and credentials are mutually exclusive"
383+
)
352384

353385
# Save or instantiate the transport.
354386
# Ordinarily, we provide the transport, but allowing a custom transport
355387
# instance provides an extensibility point for unusual situations.
356388
if isinstance(transport, ImageAnnotatorTransport):
357389
# transport is a ImageAnnotatorTransport instance.
358-
if credentials or client_options.credentials_file:
390+
if credentials or client_options.credentials_file or api_key_value:
359391
raise ValueError(
360392
"When providing a transport instance, "
361393
"provide its credentials directly."
@@ -367,6 +399,15 @@ def __init__(
367399
)
368400
self._transport = transport
369401
else:
402+
import google.auth._default # type: ignore
403+
404+
if api_key_value and hasattr(
405+
google.auth._default, "get_api_key_credentials"
406+
):
407+
credentials = google.auth._default.get_api_key_credentials(
408+
api_key_value
409+
)
410+
370411
Transport = type(self).get_transport_class(transport)
371412
self._transport = Transport(
372413
credentials=credentials,

google/cloud/vision_v1/services/product_search/async_client.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from collections import OrderedDict
1717
import functools
1818
import re
19-
from typing import Dict, Sequence, Tuple, Type, Union
19+
from typing import Dict, Optional, Sequence, Tuple, Type, Union
2020
import pkg_resources
2121

2222
from google.api_core.client_options import ClientOptions
@@ -137,6 +137,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
137137

138138
from_service_account_json = from_service_account_file
139139

140+
@classmethod
141+
def get_mtls_endpoint_and_cert_source(
142+
cls, client_options: Optional[ClientOptions] = None
143+
):
144+
"""Return the API endpoint and client cert source for mutual TLS.
145+
146+
The client cert source is determined in the following order:
147+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
148+
client cert source is None.
149+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
150+
default client cert source exists, use the default one; otherwise the client cert
151+
source is None.
152+
153+
The API endpoint is determined in the following order:
154+
(1) if `client_options.api_endpoint` if provided, use the provided one.
155+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
156+
default mTLS endpoint; if the environment variabel is "never", use the default API
157+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
158+
use the default API endpoint.
159+
160+
More details can be found at https://google.aip.dev/auth/4114.
161+
162+
Args:
163+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
164+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
165+
in this method.
166+
167+
Returns:
168+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
169+
client cert source to use.
170+
171+
Raises:
172+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
173+
"""
174+
return ProductSearchClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
175+
140176
@property
141177
def transport(self) -> ProductSearchTransport:
142178
"""Returns the transport used by the client instance.

0 commit comments

Comments
 (0)
0