7
7
import json
8
8
import requests
9
9
import urllib .parse
10
+ from requests .adapters import HTTPAdapter
10
11
11
12
_UNICODE_STRING = str
12
13
@@ -24,6 +25,31 @@ def default(self, o):
24
25
return (str (o ),)
25
26
return super (DecimalEncoder , self ).default (o )
26
27
28
+ class CustomSession (requests .Session ):
29
+ def __init__ (self ):
30
+ super ().__init__ ()
31
+ self .mount ('http://' , HTTPAdapter ())
32
+ self .mount ('https://' , HTTPAdapter ())
33
+
34
+ def prepare_request (self , request ):
35
+ # Prepare the request to access the body
36
+ prepared_request = super ().prepare_request (request )
37
+
38
+ # Remove None values from JSON payload
39
+ if prepared_request .headers .get ('Content-Type' ) == 'application/json' and prepared_request .body :
40
+ try :
41
+ data = json .loads (prepared_request .body )
42
+ cleaned_data = self ._remove_none_values (data )
43
+ prepared_request .body = json .dumps (cleaned_data )
44
+ except json .JSONDecodeError :
45
+ pass
46
+ return prepared_request
47
+
48
+ @staticmethod
49
+ def _remove_none_values (d : Dict [str , Any ]) -> Dict [str , Any ]:
50
+ """Remove keys with None values from a dictionary."""
51
+ return {k : v for k , v in d .items () if v is not None }
52
+
27
53
class Client (object ):
28
54
29
55
def __init__ (
@@ -47,7 +73,7 @@ def __init__(
47
73
if api_key is None :
48
74
api_key = authsignal .api_key
49
75
50
- self .session = session or requests . Session ()
76
+ self .session = session or CustomSession ()
51
77
self .api_key = api_key
52
78
self .url = api_url
53
79
self .timeout = timeout
@@ -241,17 +267,12 @@ def validate_challenge(self, token: str, user_id: Optional[str] = None, action:
241
267
'Accept' : 'application/json'
242
268
}
243
269
244
- payload = {'token' : token }
245
- if user_id is not None :
246
- payload ['userId' ] = user_id
247
- if action is not None :
248
- payload ['action' ] = action
249
270
250
271
try :
251
272
response = self .session .post (
252
273
path ,
253
274
auth = requests .auth .HTTPBasicAuth (self .api_key , '' ),
254
- data = json .dumps (payload ),
275
+ data = json .dumps ({ 'token' : token , 'userId' : user_id , 'action' : action } ),
255
276
headers = headers ,
256
277
timeout = self .timeout
257
278
)
0 commit comments