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

Allow EarthRanger client to be inited from a token #287

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 0 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ jobs:
# https://github.com/mamba-org/setup-micromamba/issues/227
micromamba-version: 1.5.10-0
environment-file: ${{ matrix.env }}
cache-environment: true
cache-downloads: true

- name: Test
env:
Expand Down
7 changes: 6 additions & 1 deletion ecoscope/io/async_earthranger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


class AsyncEarthRangerIO(AsyncERClient):
def __init__(self, sub_page_size=4000, tcp_limit=5, **kwargs):
def __init__(self, sub_page_size=4000, tcp_limit=5, existing_session=None, **kwargs):
if "server" in kwargs:
server = kwargs.pop("server")
kwargs["service_root"] = f"{server}/api/v1.0"
Expand All @@ -30,6 +30,11 @@ def __init__(self, sub_page_size=4000, tcp_limit=5, **kwargs):
kwargs["client_id"] = kwargs.get("client_id", "das_web_client")
super().__init__(**kwargs)

if existing_session is not None:
if isinstance(existing_session, str):
existing_session = json.loads(existing_session)
self.auth = existing_session

async def get_sources(
self,
manufacturer_id=None,
Expand Down
15 changes: 11 additions & 4 deletions ecoscope/io/earthranger.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


class EarthRangerIO(ERClient):
def __init__(self, sub_page_size=4000, tcp_limit=5, **kwargs):
def __init__(self, sub_page_size=4000, tcp_limit=5, existing_session=None, **kwargs):
if "server" in kwargs:
server = kwargs.pop("server")
kwargs["service_root"] = f"{server}/api/v1.0"
Expand All @@ -34,22 +34,29 @@ def __init__(self, sub_page_size=4000, tcp_limit=5, **kwargs):
self.tcp_limit = tcp_limit
kwargs["client_id"] = kwargs.get("client_id", "das_web_client")
super().__init__(**kwargs)

try:
self.login()
if existing_session is not None:
if isinstance(existing_session, str):
existing_session = json.loads(existing_session)
self.auth = existing_session
self.refresh_token()
else:
self.login()
except ERClientNotFound:
raise ERClientNotFound("Failed login. Check Stack Trace for specific reason.")

def _token_request(self, payload):
response = requests.post(self.token_url, data=payload)
if response.ok:
self.auth = json.loads(response.text)
self.auth = response.json()
expires_in = int(self.auth["expires_in"]) - 5 * 60
self.auth_expires = pytz.utc.localize(datetime.datetime.utcnow()) + datetime.timedelta(seconds=expires_in)
return True

self.auth = None
self.auth_expires = pytz.utc.localize(datetime.datetime.min)
raise ERClientNotFound(json.loads(response.text)["error_description"])
raise ERClientNotFound(response.json().get("error_description", "invalid token"))

"""
GET Functions
Expand Down
25 changes: 25 additions & 0 deletions tests/test_asyncearthranger_io.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import json

import pandas as pd
import pytest
Expand Down Expand Up @@ -251,3 +252,27 @@ async def test_display_map(er_io_async):
await er_io_async.get_event_type_display_name(event_type="shot_rep", event_property="shotrep_timeofshot")
== "Time when shot was heard"
)


@pytest.mark.asyncio
async def test_existing_session(er_io_async):
await er_io_async.login()
new_client = ecoscope.io.AsyncEarthRangerIO(
service_root=er_io_async.service_root, token_url=er_io_async.token_url, existing_session=er_io_async.auth
)

sources = await new_client.get_sources_dataframe()
assert not sources.empty


@pytest.mark.asyncio
async def test_existing_session_string_token(er_io_async):
await er_io_async.login()
new_client = ecoscope.io.AsyncEarthRangerIO(
service_root=er_io_async.service_root,
token_url=er_io_async.token_url,
existing_session=json.dumps(er_io_async.auth),
)

sources = await new_client.get_sources_dataframe()
assert not sources.empty
31 changes: 31 additions & 0 deletions tests/test_earthranger_io.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import uuid
import json

import geopandas as gpd
import pandas as pd
Expand Down Expand Up @@ -291,3 +292,33 @@ def test_get_subjects_chunking(er_io):
chunked_request_result = er_io.get_subjects(id=subject_ids, max_ids_per_request=1)

pd.testing.assert_frame_equal(single_request_result, chunked_request_result)


def test_existing_session(er_io):
new_client = ecoscope.io.EarthRangerIO(
service_root=er_io.service_root, token_url=er_io.token_url, existing_session=er_io.auth
)

events = new_client.get_patrol_events(
since=pd.Timestamp("2017-01-01").isoformat(),
until=pd.Timestamp("2017-04-01").isoformat(),
)
assert not events.empty

# Because er_io is session scoped, refresh token here to restore the jwt
er_io.refresh_token()


def test_existing_session_string_token(er_io):
new_client = ecoscope.io.EarthRangerIO(
service_root=er_io.service_root, token_url=er_io.token_url, existing_session=json.dumps(er_io.auth)
)

events = new_client.get_patrol_events(
since=pd.Timestamp("2017-01-01").isoformat(),
until=pd.Timestamp("2017-04-01").isoformat(),
)
assert not events.empty

# Because er_io is session scoped, refresh token here to restore the jwt
er_io.refresh_token()
Loading