Skip to content

Commit

Permalink
fix: add error handling if connecting to OdkCentral fails
Browse files Browse the repository at this point in the history
  • Loading branch information
spwoodcock committed Apr 19, 2024
1 parent 858d68b commit 05ba6d7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
24 changes: 15 additions & 9 deletions osm_fieldwork/OdkCentral.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,18 +185,24 @@ def authenticate(
self.session.headers.update({"accept": "odkcentral"})

# Get a session token
response = self.session.post(
f"{self.base}sessions",
json={
"email": self.user,
"password": self.passwd,
},
)
try:
response = self.session.post(
f"{self.base}sessions",
json={
"email": self.user,
"password": self.passwd,
},
)
except requests.exceptions.ConnectionError as request_error:
# URL does not exist
raise ConnectionError("Failed to connect to Central. Is the URL valid?") from request_error

if response.status_code == 401:
# Unauthorized, invalid credentials
raise ValueError("ODK credentials are invalid, or may have been updated. Please update them.")
raise ConnectionError("ODK credentials are invalid, or may have changed. Please update them.") from None
elif not response.ok:
response.raise_for_status() # Handle other errors
# Handle other errors
response.raise_for_status()

self.session.headers.update({"Authorization": f"Bearer {response.json().get('token')}"})

Expand Down
15 changes: 12 additions & 3 deletions osm_fieldwork/OdkCentralAsync.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,18 @@ async def __aexit__(self, exc_type, exc_value, traceback):

async def authenticate(self):
"""Authenticate to an ODK Central server."""
async with self.session.post(f"{self.base}sessions", json={"email": self.user, "password": self.passwd}) as response:
token = (await response.json())["token"]
self.session.headers.update({"Authorization": f"Bearer {token}"})
try:
async with self.session.post(f"{self.base}sessions", json={"email": self.user, "password": self.passwd}) as response:
token = (await response.json())["token"]
self.session.headers.update({"Authorization": f"Bearer {token}"})
except aiohttp.ClientConnectorError as request_error:
await self.session.close()
raise ConnectionError("Failed to connect to Central. Is the URL valid?") from request_error
except aiohttp.ClientResponseError as response_error:
await self.session.close()
if response_error.status == 401:
raise ConnectionError("ODK credentials are invalid, or may have changed. Please update them.") from response_error
raise response_error


class OdkProject(OdkCentral):
Expand Down

0 comments on commit 05ba6d7

Please sign in to comment.