1
+ from dotenv import load_dotenv
1
2
import json
2
3
import os
4
+ from pathlib import Path
3
5
import re
4
6
import requests
5
7
from urllib .parse import urlencode
@@ -13,14 +15,10 @@ def __init__(self, xdmod_host):
13
15
_validator ._assert_str ('xdmod_host' , xdmod_host )
14
16
xdmod_host = re .sub ('/+$' , '' , xdmod_host )
15
17
self .__xdmod_host = xdmod_host
16
- try :
18
+ self .__api_token = None
19
+ if 'XDMOD_API_TOKEN' in os .environ :
17
20
self .__api_token = os .environ ['XDMOD_API_TOKEN' ]
18
- except KeyError :
19
- raise KeyError (
20
- '`XDMOD_API_TOKEN` environment variable has not been set.' ,
21
- ) from None
22
21
self .__headers = {
23
- 'Authorization' : 'Bearer ' + self .__api_token ,
24
22
'User-Agent' : __title__ + ' Python v' + __version__ ,
25
23
}
26
24
self .__requests_session = None
@@ -124,17 +122,35 @@ def __assert_connection_to_xdmod_host(self):
124
122
def __request (self , path = '' , post_fields = None , stream = False ):
125
123
_validator ._assert_runtime_context (self .__in_runtime_context )
126
124
url = self .__xdmod_host + path
125
+ token_error_msg = (
126
+ 'If running in JupyterHub connected with XDMoD, there is likely an'
127
+ + ' error with the JupyterHub. Otherwise, the '
128
+ + ' `XDMOD_API_TOKEN` environment variable should be set'
129
+ + ' to a valid API token obtained from the XDMoD web portal.' ,
130
+ )
131
+ if self .__api_token is not None :
132
+ token = self .__api_token
133
+ else :
134
+ try :
135
+ load_dotenv (Path (os .path .expanduser ('~/.xdmod-jwt.env' )))
136
+ token = os .environ ['XDMOD_JWT' ]
137
+ # TODO: add test for file not existing.
138
+ except KeyError :
139
+ raise KeyError (token_error_msg ) from None
140
+ headers = {
141
+ ** self .__headers ,
142
+ ** {
143
+ 'Authorization' : 'Bearer ' + token ,
144
+ }
145
+ }
127
146
if post_fields :
128
- post_fields ['Bearer' ] = self .__api_token
129
147
response = self .__requests_session .post (
130
148
url ,
131
- headers = self . __headers ,
149
+ headers = headers ,
132
150
data = post_fields ,
133
151
)
134
152
else :
135
- url += '&' if '?' in url else '?'
136
- url += 'Bearer=' + self .__api_token
137
- response = self .__requests_session .get (url , headers = self .__headers )
153
+ response = self .__requests_session .get (url , headers = headers )
138
154
if response .status_code != 200 :
139
155
msg = ''
140
156
try :
@@ -144,7 +160,7 @@ def __request(self, path='', post_fields=None, stream=False):
144
160
pass
145
161
if response .status_code == 401 :
146
162
msg = (
147
- ': Make sure XDMOD_API_TOKEN is set to a valid API token.'
163
+ ': ' + token_error_msg
148
164
)
149
165
raise RuntimeError (
150
166
'Error ' + str (response .status_code ) + msg ,
0 commit comments