Skip to content

Commit 38c3b18

Browse files
committed
refactor: simplify code after rebase
1 parent 0c95d0d commit 38c3b18

File tree

4 files changed

+78
-86
lines changed

4 files changed

+78
-86
lines changed

gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2

Lines changed: 74 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22

33
{% block content %}
44
import abc
5-
import re
6-
import typing
5+
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
76
import packaging.version
87
import pkg_resources
98

@@ -58,15 +57,15 @@ class {{ service.name }}Transport(abc.ABC):
5857
{%- endfor %}
5958
)
6059

61-
DEFAULT_HOST = {% if service.host %}'{{ service.host }}'{% else %}{{ None }}{% endif %}
60+
DEFAULT_HOST: str = {% if service.host %}'{{ service.host }}'{% else %}{{ '' }}{% endif %}
6261

6362
def __init__(
6463
self, *,
6564
host: str = DEFAULT_HOST,
6665
credentials: credentials.Credentials = None,
67-
credentials_file: typing.Optional[str] = None,
68-
scopes: typing.Optional[typing.Sequence[str]] = None,
69-
quota_project_id: typing.Optional[str] = None,
66+
credentials_file: Optional[str] = None,
67+
scopes: Optional[Sequence[str]] = None,
68+
quota_project_id: Optional[str] = None,
7069
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
7170
**kwargs,
7271
) -> None:
@@ -97,27 +96,10 @@ class {{ service.name }}Transport(abc.ABC):
9796
host += ':443'
9897
self._host = host
9998

100-
# Save the scopes.
101-
self._scopes = scopes or self.AUTH_SCOPES
102-
# If a custom API endpoint is set, set scopes to ensure the auth
103-
# library does not used the self-signed JWT flow for service
104-
# accounts
105-
if (
106-
host is not None
107-
and self.DEFAULT_HOST is not None
108-
and host.split(":")[0] != self.DEFAULT_HOST.split(":")[0]
109-
and not scopes
110-
):
111-
scopes = self.AUTH_SCOPES
99+
scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
112100

113-
# TODO: Remove this if/else once google-auth >= 1.25.0 is required
114-
if _GOOGLE_AUTH_VERSION and (
115-
packaging.version.parse(_GOOGLE_AUTH_VERSION)
116-
>= packaging.version.parse("1.25.0")
117-
):
118-
scopes_kwargs = {"scopes": self._scopes, "default_scopes": self.AUTH_SCOPES}
119-
else:
120-
scopes_kwargs = {"scopes": self._scopes}
101+
# Save the scopes.
102+
self._scopes = scopes_kwargs["scopes"]
121103

122104
# If no credentials are provided, then determine the appropriate
123105
# defaults.
@@ -138,6 +120,62 @@ class {{ service.name }}Transport(abc.ABC):
138120
self._credentials = credentials
139121

140122

123+
@classmethod
124+
def _get_user_scopes(cls, host: str, scopes: Optional[Sequence[str]]) -> Optional[Sequence[str]]:
125+
if scopes is None:
126+
# If a custom API endpoint is set, set user scopes to ensure the auth
127+
# library does not used the self-signed JWT flow for service
128+
# accounts.
129+
if host.split(":")[0] != cls.DEFAULT_HOST.split(":")[0]:
130+
scopes = cls.AUTH_SCOPES
131+
132+
return scopes
133+
134+
135+
# TODO(busunkim): These two class methods are in the base transport
136+
# to avoid duplicating code across the transport classes. These functions
137+
# should be deleted once the minimum required versions of google-api-core
138+
# and google-auth are increased.
139+
140+
# TODO: Remove this function once google-auth >= 1.25.0 is required
141+
@classmethod
142+
def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]:
143+
"""Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
144+
145+
scopes = cls._get_user_scopes(host, scopes)
146+
scopes_kwargs = {}
147+
148+
if _GOOGLE_AUTH_VERSION and (
149+
packaging.version.parse(_GOOGLE_AUTH_VERSION)
150+
>= packaging.version.parse("1.25.0")
151+
):
152+
scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
153+
else:
154+
scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
155+
156+
return scopes_kwargs
157+
158+
# TODO: Remove this function once google-api-core >= 1.26.0 is required
159+
@classmethod
160+
def _get_self_signed_jwt_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Union[Optional[Sequence[str]], str]]:
161+
"""Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version"""
162+
scopes = cls._get_user_scopes(host, scopes)
163+
164+
self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {}
165+
166+
if _API_CORE_VERSION and (
167+
packaging.version.parse(_API_CORE_VERSION)
168+
>= packaging.version.parse("1.26.0")
169+
):
170+
self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES
171+
self_signed_jwt_kwargs["scopes"] = scopes
172+
self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST
173+
else:
174+
self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES
175+
176+
return self_signed_jwt_kwargs
177+
178+
141179
def _prep_wrapped_messages(self, client_info):
142180
# Precompute the wrapped methods.
143181
self._wrapped_methods = {
@@ -173,11 +211,11 @@ class {{ service.name }}Transport(abc.ABC):
173211
{%- for method in service.methods.values() %}
174212

175213
@property
176-
def {{ method.name|snake_case }}(self) -> typing.Callable[
214+
def {{ method.name|snake_case }}(self) -> Callable[
177215
[{{ method.input.ident }}],
178-
typing.Union[
216+
Union[
179217
{{ method.output.ident }},
180-
typing.Awaitable[{{ method.output.ident }}]
218+
Awaitable[{{ method.output.ident }}]
181219
]]:
182220
raise NotImplementedError()
183221
{%- endfor %}
@@ -187,29 +225,29 @@ class {{ service.name }}Transport(abc.ABC):
187225
@property
188226
def set_iam_policy(
189227
self,
190-
) -> typing.Callable[
228+
) -> Callable[
191229
[iam_policy.SetIamPolicyRequest],
192-
typing.Union[policy.Policy, typing.Awaitable[policy.Policy]],
230+
Union[policy.Policy, Awaitable[policy.Policy]],
193231
]:
194232
raise NotImplementedError()
195233

196234
@property
197235
def get_iam_policy(
198236
self,
199-
) -> typing.Callable[
237+
) -> Callable[
200238
[iam_policy.GetIamPolicyRequest],
201-
typing.Union[policy.Policy, typing.Awaitable[policy.Policy]],
239+
Union[policy.Policy, Awaitable[policy.Policy]],
202240
]:
203241
raise NotImplementedError()
204242

205243
@property
206244
def test_iam_permissions(
207245
self,
208-
) -> typing.Callable[
246+
) -> Callable[
209247
[iam_policy.TestIamPermissionsRequest],
210-
typing.Union[
248+
Union[
211249
iam_policy.TestIamPermissionsResponse,
212-
typing.Awaitable[iam_policy.TestIamPermissionsResponse],
250+
Awaitable[iam_policy.TestIamPermissionsResponse],
213251
],
214252
]:
215253
raise NotImplementedError()

gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc.py.j2

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore
2828
{% endif %}
2929
{% endfilter %}
3030
from .base import {{ service.name }}Transport, DEFAULT_CLIENT_INFO
31-
from .base import _GOOGLE_AUTH_VERSION, _API_CORE_VERSION
3231

3332

3433
class {{ service.name }}GrpcTransport({{ service.name }}Transport):
@@ -205,29 +204,8 @@ class {{ service.name }}GrpcTransport({{ service.name }}Transport):
205204
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
206205
and ``credentials_file`` are passed.
207206
"""
208-
# If a custom API endpoint is set, set scopes to ensure the auth
209-
# library does not used the self-signed JWT flow for service
210-
# accounts
211-
if (
212-
host is not None
213-
and cls.DEFAULT_HOST is not None
214-
and host.split(":")[0] != cls.DEFAULT_HOST.split(":")[0]
215-
and not scopes
216-
):
217-
scopes = cls.AUTH_SCOPES
218-
219-
self_signed_jwt_kwargs = {} # type: Dict[str, Union[Optional[Sequence[str]], str]]
220-
221-
# TODO(busunkim): Remove this if/else once google-api-core >= 1.26.0 is required
222-
if _API_CORE_VERSION and (
223-
packaging.version.parse(_API_CORE_VERSION)
224-
>= packaging.version.parse("1.26.0")
225-
):
226-
self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES
227-
self_signed_jwt_kwargs["scopes"] = scopes
228-
self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST
229-
else:
230-
self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES
207+
208+
self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes)
231209

232210
return grpc_helpers.create_channel(
233211
host,

gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/grpc_asyncio.py.j2

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore
2828
{% endif %}
2929
{% endfilter %}
3030
from .base import {{ service.name }}Transport, DEFAULT_CLIENT_INFO
31-
from .base import _GOOGLE_AUTH_VERSION, _API_CORE_VERSION
3231
from .grpc import {{ service.name }}GrpcTransport
3332

3433

@@ -77,29 +76,8 @@ class {{ service.grpc_asyncio_transport_name }}({{ service.name }}Transport):
7776
Returns:
7877
aio.Channel: A gRPC AsyncIO channel object.
7978
"""
80-
# If a custom API endpoint is set, set scopes to ensure the auth
81-
# library does not used the self-signed JWT flow for service
82-
# accounts
83-
if (
84-
host is not None
85-
and cls.DEFAULT_HOST is not None
86-
and host.split(":")[0] != cls.DEFAULT_HOST.split(":")[0]
87-
and not scopes
88-
):
89-
scopes = cls.AUTH_SCOPES
90-
91-
self_signed_jwt_kwargs = {} # type: Dict[str, Union[Optional[Sequence[str]], str]]
92-
93-
# TODO(busunkim): Remove this if/else once google-api-core >= 1.26.0 is required
94-
if _API_CORE_VERSION and (
95-
packaging.version.parse(_API_CORE_VERSION)
96-
>= packaging.version.parse("1.26.0")
97-
):
98-
self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES
99-
self_signed_jwt_kwargs["scopes"] = scopes
100-
self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST
101-
else:
102-
self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES
79+
80+
self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes)
10381

10482
return grpc_helpers_async.create_channel(
10583
host,

gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ from google.oauth2 import service_account
2525
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }} import {{ service.client_name }}
2626
{%- if 'grpc' in opts.transport %}
2727
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }} import {{ service.async_client_name }}
28-
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.transports.grpc import _GOOGLE_AUTH_VERSION
29-
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.transports.grpc import _API_CORE_VERSION
3028
{%- endif %}
3129
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }} import transports
3230
from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.transports.base import _GOOGLE_AUTH_VERSION

0 commit comments

Comments
 (0)