Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Omit null values from requests by default #26

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions authsignal/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import requests
import urllib.parse
from requests.adapters import HTTPAdapter

_UNICODE_STRING = str

Expand All @@ -24,6 +25,31 @@ def default(self, o):
return (str(o),)
return super(DecimalEncoder, self).default(o)

class CustomSession(requests.Session):
def __init__(self):
super().__init__()
self.mount('http://', HTTPAdapter())
self.mount('https://', HTTPAdapter())

def prepare_request(self, request):
# Prepare the request to access the body
prepared_request = super().prepare_request(request)

# Remove None values from JSON payload
if prepared_request.headers.get('Content-Type') == 'application/json' and prepared_request.body:
try:
data = json.loads(prepared_request.body)
cleaned_data = self._remove_none_values(data)
prepared_request.body = json.dumps(cleaned_data)
except json.JSONDecodeError:
pass
return prepared_request

@staticmethod
def _remove_none_values(d: Dict[str, Any]) -> Dict[str, Any]:
"""Remove keys with None values from a dictionary."""
return {k: v for k, v in d.items() if v is not None}

class Client(object):

def __init__(
Expand All @@ -47,7 +73,7 @@ def __init__(
if api_key is None:
api_key = authsignal.api_key

self.session = session or requests.Session()
self.session = session or CustomSession()
self.api_key = api_key
self.url = api_url
self.timeout = timeout
Expand Down Expand Up @@ -241,17 +267,12 @@ def validate_challenge(self, token: str, user_id: Optional[str] = None, action:
'Accept': 'application/json'
}

payload = {'token': token}
if user_id is not None:
payload['userId'] = user_id
if action is not None:
payload['action'] = action

try:
response = self.session.post(
path,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
data=json.dumps(payload),
data=json.dumps({'token': token, 'userId': user_id, 'action': action}),
headers=headers,
timeout=self.timeout
)
Expand Down
Loading