44(ie. BigQuery).
55"""
66
7- import json
87import os
9- import socket
10- import urllib .request
118from datetime import datetime , timedelta
129from enum import Enum , unique
1310from typing import Optional , Tuple
14- from urllib .error import HTTPError , URLError
15-
16- _KAGGLE_DEFAULT_URL_BASE = "https://www.kaggle.com"
17- _KAGGLE_URL_BASE_ENV_VAR_NAME = "KAGGLE_URL_BASE"
18- _KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME = "KAGGLE_USER_SECRETS_TOKEN"
19- TIMEOUT_SECS = 40
20-
21-
22- class CredentialError (Exception ):
23- pass
24-
25-
26- class BackendError (Exception ):
27- pass
28-
11+ from kaggle_web_client import KaggleWebClient
12+ from kaggle_web_client import (CredentialError , BackendError )
2913
3014class ValidationError (Exception ):
3115 pass
@@ -56,48 +40,9 @@ def service(self):
5640class UserSecretsClient ():
5741 GET_USER_SECRET_ENDPOINT = '/requests/GetUserSecretRequest'
5842 GET_USER_SECRET_BY_LABEL_ENDPOINT = '/requests/GetUserSecretByLabelRequest'
59- BIGQUERY_TARGET_VALUE = 1
6043
6144 def __init__ (self ):
62- url_base_override = os .getenv (_KAGGLE_URL_BASE_ENV_VAR_NAME )
63- self .url_base = url_base_override or _KAGGLE_DEFAULT_URL_BASE
64- # Follow the OAuth 2.0 Authorization standard (https://tools.ietf.org/html/rfc6750)
65- self .jwt_token = os .getenv (_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME )
66- if self .jwt_token is None :
67- raise CredentialError (
68- 'A JWT Token is required to use the UserSecretsClient, '
69- f'but none found in environment variable { _KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME } ' )
70- self .headers = {'Content-type' : 'application/json' }
71-
72- def _make_post_request (self , data : dict , endpoint : str = GET_USER_SECRET_ENDPOINT ) -> dict :
73- # TODO(b/148309982) This code and the code in the constructor should be
74- # removed and this class should use the new KaggleWebClient class instead.
75- url = f'{ self .url_base } { endpoint } '
76- request_body = dict (data )
77- request_body ['JWE' ] = self .jwt_token
78- req = urllib .request .Request (url , headers = self .headers , data = bytes (
79- json .dumps (request_body ), encoding = "utf-8" ))
80- try :
81- with urllib .request .urlopen (req , timeout = TIMEOUT_SECS ) as response :
82- response_json = json .loads (response .read ())
83- if not response_json .get ('wasSuccessful' ) or 'result' not in response_json :
84- raise BackendError (
85- f'Unexpected response from the service. Response: { response_json } .' )
86- return response_json ['result' ]
87- except (URLError , socket .timeout ) as e :
88- if isinstance (
89- e , socket .timeout ) or isinstance (
90- e .reason , socket .timeout ):
91- raise ConnectionError (
92- 'Timeout error trying to communicate with service. Please ensure internet is on.' ) from e
93- raise ConnectionError (
94- 'Connection error trying to communicate with service.' ) from e
95- except HTTPError as e :
96- if e .code == 401 or e .code == 403 :
97- raise CredentialError (
98- f'Service responded with error code { e .code } .'
99- ' Please ensure you have access to the resource.' ) from e
100- raise BackendError ('Unexpected response from the service.' ) from e
45+ self .web_client = KaggleWebClient ()
10146
10247 def get_secret (self , label ) -> str :
10348 """Retrieves a user secret value by its label.
@@ -113,7 +58,7 @@ def get_secret(self, label) -> str:
11358 request_body = {
11459 'Label' : label ,
11560 }
116- response_json = self ._make_post_request (request_body , self .GET_USER_SECRET_BY_LABEL_ENDPOINT )
61+ response_json = self .web_client . make_post_request (request_body , self .GET_USER_SECRET_BY_LABEL_ENDPOINT )
11762 if 'secret' not in response_json :
11863 raise BackendError (
11964 f'Unexpected response from the service. Response: { response_json } ' )
@@ -174,7 +119,7 @@ def _get_access_token(self, target: GcpTarget) -> Tuple[str, Optional[datetime]]
174119 request_body = {
175120 'Target' : target .target
176121 }
177- response_json = self ._make_post_request (request_body )
122+ response_json = self .web_client . make_post_request (request_body , self . GET_USER_SECRET_ENDPOINT )
178123 if 'secret' not in response_json :
179124 raise BackendError (
180125 f'Unexpected response from the service. Response: { response_json } ' )
0 commit comments