Skip to content

Commit b9270be

Browse files
SholoflyRudolf Offereins
andauthored
Environment selection (#17)
* 🧹 Less generic name for token file * ✨ Option to choose between staging and production API * ⚡ Update test and example Co-authored-by: Rudolf Offereins <rudolf.offereins@netivity.nl>
1 parent 8eb4049 commit b9270be

7 files changed

Lines changed: 64 additions & 46 deletions

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,5 @@ var/
1818
logs/
1919
__pycache__/
2020
.pytest_cache/
21-
token.py
21+
my_token.py
2222
.pypirc

examples/control.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
"""Asynchronous Python client for the Geocaching API."""
22
import asyncio
33
from geocachingapi import GeocachingApi
4+
from geocachingapi.models import GeocachingApiEnvironment
45

56
async def main():
67
"""Show example of using the Geocaching API"""
7-
async with GeocachingApi() as api:
8-
print("test")
8+
async with GeocachingApi(token="<insert your token here>", environment=GeocachingApiEnvironment.Staging) as api:
9+
status = await api.update()
10+
print(status.user.reference_code)
911

1012
if __name__ == "__main__":
1113
loop = asyncio.get_event_loop()
12-
loop.run_until_complete(main())
14+
loop.run_until_complete(main())
15+

geocachingapi/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
"""Python client for connecting to the Geocaching API"""
22
from .geocachingapi import GeocachingApi
3-
from .models import GeocachingSettings, GeocachingStatus
3+
from .models import GeocachingSettings, GeocachingStatus, GeocachingApiEnvironment

geocachingapi/const.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
"""Geocaching Api Constants."""
2-
GEOCACHING_API_SCHEME = "https"
3-
GEOCACHING_API_HOST = "staging.api.groundspeak.com"
4-
GEOCACHING_API_PORT = 443
5-
GEOCACHING_API_BASE_PATH = "/"
6-
GEOCACHING_API_VERSION = "v1"
2+
from .models import GeocachingApiEnvironment, GeocachingApiEnvironmentSettings
3+
4+
ENVIRONMENT_SETTINGS = {
5+
GeocachingApiEnvironment.Staging : GeocachingApiEnvironmentSettings(
6+
api_scheme= "https",
7+
api_host= "staging.api.groundspeak.com",
8+
api_port = 443,
9+
api_base_bath="/v1",
10+
),
11+
12+
GeocachingApiEnvironment.Production : GeocachingApiEnvironmentSettings(
13+
api_scheme= "https",
14+
api_host= "api.groundspeak.com",
15+
api_port = 443,
16+
api_base_bath="/v1",
17+
)
18+
}
719

820
MEMBERSHIP_LEVELS = {
921
0: "Unknown",

geocachingapi/geocachingapi.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,7 @@
1212
from aiohttp import ClientResponse, ClientSession, ClientError
1313

1414
from typing import Any, Awaitable, Callable, Dict, List, Optional
15-
from .const import (
16-
GEOCACHING_API_BASE_PATH,
17-
GEOCACHING_API_HOST,
18-
GEOCACHING_API_PORT,
19-
GEOCACHING_API_SCHEME,
20-
GEOCACHING_API_VERSION,
21-
)
15+
from .const import ENVIRONMENT_SETTINGS
2216
from .exceptions import (
2317
GeocachingApiConnectionError,
2418
GeocachingApiConnectionTimeoutError,
@@ -28,7 +22,9 @@
2822

2923
from .models import (
3024
GeocachingStatus,
31-
GeocachingSettings
25+
GeocachingSettings,
26+
GeocachingApiEnvironment,
27+
GeocachingApiEnvironmentSettings
3228
)
3329

3430
_LOGGER = logging.getLogger(__name__)
@@ -38,9 +34,11 @@ class GeocachingApi:
3834
_close_session: bool = False
3935
_status: GeocachingStatus = None
4036
_settings: GeocachingSettings = None
37+
_environment_settings: GeocachingApiEnvironmentSettings = None
4138
def __init__(
4239
self,
4340
*,
41+
environment: GeocachingApiEnvironment,
4442
token: str,
4543
settings: GeocachingSettings = None,
4644
request_timeout: int = 8,
@@ -49,6 +47,7 @@ def __init__(
4947

5048
) -> None:
5149
"""Initialize connection with the Geocaching API."""
50+
self._environment_settings = ENVIRONMENT_SETTINGS[environment]
5251
self._status = GeocachingStatus()
5352
self._settings = settings or GeocachingSettings(False)
5453
self._session = session
@@ -67,11 +66,12 @@ async def _request(self, method, uri, **kwargs) -> ClientResponse:
6766
_LOGGER.debug(f'Token refresh method called.')
6867

6968
url = URL.build(
70-
scheme=GEOCACHING_API_SCHEME,
71-
host=GEOCACHING_API_HOST,
72-
port=GEOCACHING_API_PORT,
73-
path=GEOCACHING_API_BASE_PATH,
74-
).join(URL(uri))
69+
scheme=self._environment_settings["api_scheme"],
70+
host=self._environment_settings["api_host"],
71+
port=self._environment_settings["api_port"],
72+
path=self._environment_settings["api_base_bath"],
73+
)
74+
url = str(url) + uri
7575
_LOGGER.debug(f'Executing {method} API request to {url}.')
7676
headers = kwargs.get("headers")
7777

@@ -155,7 +155,7 @@ async def _update_user(self, data: Dict[str, Any] = None) -> None:
155155
"awardedFavoritePoints",
156156
"membershipLevelId"
157157
])
158-
data = await self._request("GET", f"/{GEOCACHING_API_VERSION}/users/me?fields={fields}")
158+
data = await self._request("GET", f"/users/me?fields={fields}")
159159
self._status.update_user_from_dict(data)
160160
_LOGGER.debug(f'User updated.')
161161

geocachingapi/models.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
11
from __future__ import annotations
2-
from typing import Any, Dict, Optional
2+
from enum import Enum
3+
from typing import Any, Dict, Optional, TypedDict
34

45
from dataclasses import dataclass
56
from datetime import datetime
67
from .utils import try_get_from_dict
78

9+
class GeocachingApiEnvironmentSettings(TypedDict):
10+
"""Class to represent API environment settings"""
11+
api_scheme:str
12+
api_host:str
13+
api_port: int
14+
api_base_bath:str
15+
16+
class GeocachingApiEnvironment(Enum):
17+
"""Enum to represent API environment"""
18+
Staging = 1,
19+
Production = 2,
820

921
class GeocachingSettings:
1022
"""Class to hold the Geocaching Api settings"""
11-
fetch_trackables: bool = False
12-
def __init__(self, fetch_trackables:bool = False) -> None:
23+
fetch_trackables: bool
24+
environment: GeocachingApiEnvironment
25+
26+
def __init__(self, fetch_trackables:bool = False, environment:GeocachingApiEnvironment = GeocachingApiEnvironment.Production ) -> None:
1327
"""Initialize settings"""
1428
self.fetch_trackables = fetch_trackables
1529

16-
17-
18-
1930
@dataclass
2031
class GeocachingUser:
2132
"""Class to hold the Geocaching user information"""

tests/test.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,19 @@
11
"""Test for Geocaching Api integration."""
2-
from geocachingapi import GeocachingApi, GeocachingStatus, GeocachingSettings
3-
#For adding your token add a file call token.py to current folder and add TOKEN = "<your token here>"
4-
from .token import TOKEN
52
import asyncio
6-
import pytest
7-
8-
# @pytest.mark.asyncio
93
import logging
4+
from geocachingapi import GeocachingApi, GeocachingStatus
5+
from geocachingapi.models import GeocachingApiEnvironment
6+
from my_token import TOKEN
107
logging.basicConfig(level=logging.DEBUG)
11-
128
mylogger = logging.getLogger()
139

14-
@pytest.mark.asyncio
1510
async def test():
11+
"""Function to test GeocachingAPI integration"""
1612
status:GeocachingStatus = None
17-
api = GeocachingApi(token=TOKEN)
13+
api = GeocachingApi(token=TOKEN, environment=GeocachingApiEnvironment.Staging)
1814
status = await api.update()
1915
print(status.user.reference_code)
20-
assert(status.user.reference_code is not None)
21-
assert(status.user.find_count is not None)
2216
await api.close()
23-
assert(False)
24-
25-
26-
27-
17+
loop = asyncio.get_event_loop()
18+
loop.run_until_complete(test())
19+
loop.close()

0 commit comments

Comments
 (0)