Skip to content

Commit a8e7f47

Browse files
committed
Use kaggle-web-client for kaggle_secrets
1 parent 6afd928 commit a8e7f47

File tree

2 files changed

+21
-70
lines changed

2 files changed

+21
-70
lines changed

patches/kaggle_secrets.py

Lines changed: 5 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -4,31 +4,12 @@
44
(ie. BigQuery).
55
"""
66

7-
import json
87
import os
9-
import socket
10-
import urllib.request
118
from datetime import datetime, timedelta
129
from enum import Enum, unique
1310
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-
29-
30-
class ValidationError(Exception):
31-
pass
11+
from kaggle_web_client import KaggleWebClient
12+
from kaggle_web_client import (CredentialError, BackendError, ValidationError)
3213

3314
class NotFoundError(Exception):
3415
pass
@@ -56,48 +37,9 @@ def service(self):
5637
class UserSecretsClient():
5738
GET_USER_SECRET_ENDPOINT = '/requests/GetUserSecretRequest'
5839
GET_USER_SECRET_BY_LABEL_ENDPOINT = '/requests/GetUserSecretByLabelRequest'
59-
BIGQUERY_TARGET_VALUE = 1
6040

6141
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
42+
self.web_client = KaggleWebClient()
10143

10244
def get_secret(self, label) -> str:
10345
"""Retrieves a user secret value by its label.
@@ -113,7 +55,7 @@ def get_secret(self, label) -> str:
11355
request_body = {
11456
'Label': label,
11557
}
116-
response_json = self._make_post_request(request_body, self.GET_USER_SECRET_BY_LABEL_ENDPOINT)
58+
response_json = self.web_client.make_post_request(request_body, self.GET_USER_SECRET_BY_LABEL_ENDPOINT)
11759
if 'secret' not in response_json:
11860
raise BackendError(
11961
f'Unexpected response from the service. Response: {response_json}')
@@ -174,7 +116,7 @@ def _get_access_token(self, target: GcpTarget) -> Tuple[str, Optional[datetime]]
174116
request_body = {
175117
'Target': target.target
176118
}
177-
response_json = self._make_post_request(request_body)
119+
response_json = self.web_client.make_post_request(request_body, self.GET_USER_SECRET_ENDPOINT)
178120
if 'secret' not in response_json:
179121
raise BackendError(
180122
f'Unexpected response from the service. Response: {response_json}')

patches/kaggle_web_client.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,23 @@
22
import os
33
import socket
44
import urllib.request
5-
from datetime import datetime, timedelta
6-
from enum import Enum, unique
7-
from typing import Optional, Tuple
85
from urllib.error import HTTPError, URLError
9-
from kaggle_secrets import (_KAGGLE_DEFAULT_URL_BASE,
10-
_KAGGLE_URL_BASE_ENV_VAR_NAME,
11-
_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME,
12-
CredentialError, BackendError, ValidationError)
6+
7+
_KAGGLE_DEFAULT_URL_BASE = "https://www.kaggle.com"
8+
_KAGGLE_URL_BASE_ENV_VAR_NAME = "KAGGLE_URL_BASE"
9+
_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME = "KAGGLE_USER_SECRETS_TOKEN"
10+
TIMEOUT_SECS = 40
11+
12+
class CredentialError(Exception):
13+
pass
14+
15+
16+
class BackendError(Exception):
17+
pass
18+
19+
20+
class ValidationError(Exception):
21+
pass
1322

1423
class KaggleWebClient:
1524
TIMEOUT_SECS = 600

0 commit comments

Comments
 (0)