7
7
import json
8
8
import os
9
9
import urllib .request
10
+ from urllib .error import HTTPError
11
+ from typing import Tuple , Optional
12
+ from datetime import datetime , timedelta
10
13
11
14
_KAGGLE_DEFAULT_URL_BASE = "https://www.kaggle.com"
12
15
_KAGGLE_URL_BASE_ENV_VAR_NAME = "KAGGLE_URL_BASE"
@@ -37,7 +40,7 @@ def __init__(self):
37
40
f'but none found in environment variable { _KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME } ' )
38
41
self .headers = {'Content-type' : 'application/json' }
39
42
40
- def _make_post_request (self , data ) :
43
+ def _make_post_request (self , data : dict ) -> dict :
41
44
url = f'{ self .url_base } { self .GET_USER_SECRET_ENDPOINT } '
42
45
request_body = dict (data )
43
46
request_body ['JWE' ] = self .jwt_token
@@ -50,18 +53,29 @@ def _make_post_request(self, data):
50
53
raise BackendError (
51
54
'Unexpected response from the service.' )
52
55
return response_json ['result' ]
53
- except urllib . error . HTTPError as e :
56
+ except HTTPError as e :
54
57
if e .code == 401 or e .code == 403 :
55
58
raise CredentialError (f'Service responded with error code { e .code } .'
56
59
' Please ensure you have access to the resource.' ) from e
57
60
raise BackendError ('Unexpected response from the service.' ) from e
58
61
59
- def get_bigquery_access_token (self ):
62
+ def get_bigquery_access_token (self ) -> Tuple [str , Optional [datetime ]]:
63
+ """Retrieves BigQuery access token information from the UserSecrets service.
64
+
65
+ This returns the token for the current kernel as well as its expiry (abs time) if it
66
+ is present.
67
+ Example usage:
68
+ client = UserSecretsClient()
69
+ token, expiry = client.get_bigquery_access_token()
70
+ """
60
71
request_body = {
61
72
'Target' : self .BIGQUERY_TARGET_VALUE
62
73
}
63
74
response_json = self ._make_post_request (request_body )
64
75
if 'secret' not in response_json :
65
76
raise BackendError (
66
77
'Unexpected response from the service.' )
67
- return response_json ['secret' ]
78
+ # Optionally return expiry if it is set.
79
+ expiresInSeconds = response_json .get ('expiresInSeconds' )
80
+ expiry = datetime .utcnow () + timedelta (seconds = expiresInSeconds ) if expiresInSeconds else None
81
+ return response_json ['secret' ], expiry
0 commit comments