1313from awswrangler import _utils , exceptions
1414from awswrangler .annotations import Experimental
1515
16- opensearchpy = _utils .import_optional_dependency ("opensearchpy" )
17- if opensearchpy :
18- from requests_aws4auth import AWS4Auth
16+ if TYPE_CHECKING :
17+ try :
18+ import requests_aws4auth
19+ except ImportError :
20+ pass
21+ else :
22+ requests_aws4auth = _utils .import_optional_dependency ("requests_aws4auth" )
23+
24+ if TYPE_CHECKING :
25+ try :
26+ import opensearchpy
27+ except ImportError :
28+ pass
29+ else :
30+ opensearchpy = _utils .import_optional_dependency ("opensearchpy" )
1931
2032if TYPE_CHECKING :
2133 from mypy_boto3_opensearchserverless .client import OpenSearchServiceServerlessClient
@@ -157,6 +169,19 @@ def _create_data_policy(
157169 raise error
158170
159171
172+ @_utils .check_optional_dependency (requests_aws4auth , "requests_aws4auth" )
173+ def _build_aws4_auth (
174+ region : str , service : str , creds : botocore .credentials .ReadOnlyCredentials
175+ ) -> "requests_aws4auth.AWS4Auth" :
176+ return requests_aws4auth .AWS4Auth (
177+ creds .access_key ,
178+ creds .secret_key ,
179+ region ,
180+ service ,
181+ session_token = creds .token ,
182+ )
183+
184+
160185@_utils .check_optional_dependency (opensearchpy , "opensearchpy" )
161186def connect (
162187 host : str ,
@@ -233,7 +258,11 @@ def connect(
233258 "given. Unable to find ACCESS_KEY_ID and SECRET_ACCESS_KEY in boto3 "
234259 "session."
235260 )
236- http_auth = AWS4Auth (creds .access_key , creds .secret_key , region , service , session_token = creds .token )
261+ http_auth = _build_aws4_auth (
262+ region = region ,
263+ service = service ,
264+ creds = creds ,
265+ )
237266 try :
238267 es = opensearchpy .OpenSearch (
239268 host = _strip_endpoint (host ),
@@ -247,7 +276,7 @@ def connect(
247276 retry_on_timeout = retry_on_timeout ,
248277 retry_on_status = retry_on_status ,
249278 )
250- es ._serverless = service == "aoss" # pylint: disable=protected-access
279+ es ._serverless = service == "aoss" # type: ignore[attr-defined] # pylint: disable=protected-access
251280 except Exception as e :
252281 _logger .error ("Error connecting to Opensearch cluster. Please verify authentication details" )
253282 raise e
0 commit comments