4
4
(ie. BigQuery).
5
5
"""
6
6
7
- import json
8
7
import os
9
- import socket
10
- import urllib .request
11
8
from datetime import datetime , timedelta
12
9
from enum import Enum , unique
13
10
from 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 )
29
13
30
14
class ValidationError (Exception ):
31
15
pass
@@ -56,48 +40,9 @@ def service(self):
56
40
class UserSecretsClient ():
57
41
GET_USER_SECRET_ENDPOINT = '/requests/GetUserSecretRequest'
58
42
GET_USER_SECRET_BY_LABEL_ENDPOINT = '/requests/GetUserSecretByLabelRequest'
59
- BIGQUERY_TARGET_VALUE = 1
60
43
61
44
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 ()
101
46
102
47
def get_secret (self , label ) -> str :
103
48
"""Retrieves a user secret value by its label.
@@ -113,7 +58,7 @@ def get_secret(self, label) -> str:
113
58
request_body = {
114
59
'Label' : label ,
115
60
}
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 )
117
62
if 'secret' not in response_json :
118
63
raise BackendError (
119
64
f'Unexpected response from the service. Response: { response_json } ' )
@@ -174,7 +119,7 @@ def _get_access_token(self, target: GcpTarget) -> Tuple[str, Optional[datetime]]
174
119
request_body = {
175
120
'Target' : target .target
176
121
}
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 )
178
123
if 'secret' not in response_json :
179
124
raise BackendError (
180
125
f'Unexpected response from the service. Response: { response_json } ' )
0 commit comments