Skip to content

Commit 7042816

Browse files
authored
Automatically set the locale matching the selected API language (#93)
* add a method to set locale from the selected lang - close #91 * minor fixes before release * housekeeping dependencies
1 parent 63f5411 commit 7042816

File tree

9 files changed

+83
-72
lines changed

9 files changed

+83
-72
lines changed

Pipfile.lock

Lines changed: 29 additions & 29 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

isogeo_pysdk/api/routes_application.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def __init__(self, api_client=None):
5757
def listing(
5858
self,
5959
workgroup_id: str = None,
60-
include: list = ["_abilities"],
60+
include: list = ("_abilities"),
6161
caching: bool = 1,
6262
) -> list:
6363
"""Get all applications which are accessible by the authenticated user OR applications for a workgroup.
@@ -178,7 +178,7 @@ def create(
178178
if check_exists == 1:
179179
# retrieve workgroup applications
180180
if not self.api_client._applications_names:
181-
self.applications(include=[])
181+
self.listing(include=())
182182
# check
183183
if application.name in self.api_client._applications_names:
184184
logger.debug(

isogeo_pysdk/api/routes_condition.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
# submodules
2222
from isogeo_pysdk.checker import IsogeoChecker
2323
from isogeo_pysdk.decorators import ApiDecorators
24-
from isogeo_pysdk.models import Condition, Metadata, License
24+
from isogeo_pysdk.models import Condition, Metadata
2525
from isogeo_pysdk.utils import IsogeoUtils
2626

2727
# #############################################################################

isogeo_pysdk/api/routes_share.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,12 +246,14 @@ def exists(self, share_id: str) -> bool:
246246
else:
247247
pass
248248

249-
# URL builder
250-
url_share_exists = "{}{}".format(utils.get_request_base_url("shares"), share_id)
249+
# URL
250+
url_share_exists = utils.get_request_base_url(
251+
route="shares/{}".format(share_id)
252+
)
251253

252254
# request
253255
req_share_exists = self.api_client.get(
254-
url_share_exists,
256+
url=url_share_exists,
255257
headers=self.api_client.header,
256258
proxies=self.api_client.proxies,
257259
verify=self.api_client.ssl,

isogeo_pysdk/isogeo.py

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616
# ##################################
1717

1818
# Standard library
19-
import locale
2019
import logging
21-
from sys import platform as opersys
2220

2321
# 3rd party library
2422
from oauthlib.oauth2 import BackendApplicationClient, LegacyApplicationClient
@@ -63,7 +61,7 @@ class Isogeo(OAuth2Session):
6361
:param str auth_mode: oAuth2 authentication flow to use. Must be one of 'AUTH_MODES'
6462
:param str platform: to request production or quality assurance
6563
:param dict proxy: dictionary of proxy settings as described in `Requests <https://2.python-requests.org/en/master/user/advanced/#proxies>`_
66-
:param str lang: API localization ("en" or "fr").
64+
:param str lang: API localization ("en" or "fr"). Defaults to 'fr'.
6765
:param str app_name: to custom the application name and user-agent
6866
6967
@@ -101,7 +99,7 @@ class Isogeo(OAuth2Session):
10199
auto_refresh_url="{}/oauth/token".format(environ.get("ISOGEO_ID_URL")),
102100
platform=environ.get("ISOGEO_PLATFORM", "qa"),
103101
)
104-
102+
105103
# getting a token
106104
isogeo.connect()
107105
@@ -210,30 +208,12 @@ def __init__(
210208
# setting language
211209
if lang.lower() not in ("fr", "en"):
212210
logger.warning(
213-
"Isogeo API is only available in English ('en', "
214-
"default) or French ('fr'). "
215-
"Language has been set on English."
211+
"Isogeo API is only available in English ('en', default) or French ('fr'). Language has been set on English."
216212
)
217213
self.lang = "en"
218214
else:
219215
self.lang = lang.lower()
220-
221-
# setting locale according to the language passed
222-
# try:
223-
# if opersys == "win32":
224-
# if lang.lower() == "fr":
225-
# locale.setlocale(locale.LC_ALL, str("fra_fra"))
226-
# else:
227-
# locale.setlocale(locale.LC_ALL, str("uk_UK"))
228-
# else:
229-
# if lang.lower() == "fr":
230-
# locale.setlocale(locale.LC_ALL, str("fr_FR.utf8"))
231-
# else:
232-
# locale.setlocale(locale.LC_ALL, str("en_GB.utf8"))
233-
# except locale.Error as e:
234-
# logger.error(
235-
# "Selected locale ({}) is not installed: {}".format(lang.lower(), e)
236-
# )
216+
utils.set_lang_and_locale(self.lang)
237217

238218
# handling proxy parameters
239219
# see: http://docs.python-requests.org/en/latest/user/advanced/#proxies
@@ -364,8 +344,6 @@ def guess_auth_mode(self):
364344
from time import sleep, gmtime, strftime
365345
import urllib3
366346

367-
from isogeo_pysdk.models import Keyword, Share
368-
369347
# ------------ Log & debug ----------------
370348
logger = logging.getLogger()
371349
logging.captureWarnings(True)

isogeo_pysdk/utils.py

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# Standard library
1616
import base64
1717
import json
18+
import locale
1819
import logging
1920
import math
2021
import quopri
@@ -23,6 +24,7 @@
2324
from configparser import ConfigParser
2425
from datetime import datetime
2526
from pathlib import Path
27+
from sys import platform as opersys
2628
from urllib.parse import urlparse
2729

2830
# 3rd party
@@ -133,6 +135,8 @@ class IsogeoUtils(object):
133135
},
134136
}
135137

138+
lang = "fr"
139+
136140
def __init__(self, proxies: dict = dict()):
137141
"""Instanciate IsogeoUtils module.
138142
@@ -158,14 +162,9 @@ def set_base_url(self, platform: str = "prod"):
158162
self.platform = platform
159163
if platform == "prod":
160164
self.ssl = True
161-
logger.debug("Using production platform.")
162165
elif platform == "qa":
163166
self.ssl = False
164-
logger.debug("Using Quality Assurance platform (reduced perfs).")
165167
else:
166-
logging.error(
167-
"Platform must be one of: {}".format(" | ".join(self.API_URLS.keys()))
168-
)
169168
raise ValueError(
170169
3,
171170
"Platform must be one of: {}".format(" | ".join(self.API_URLS.keys())),
@@ -185,6 +184,34 @@ def set_base_url(self, platform: str = "prod"):
185184
self.ssl,
186185
)
187186

187+
@classmethod
188+
def set_lang_and_locale(self, lang: str):
189+
"""Set requests language and the matching locale.
190+
191+
:param str lang: language code to set API localization ("en" or "fr"). Defaults to 'fr'.
192+
"""
193+
lang = lang.lower()
194+
195+
# setting locale according to the language passed and depending on OS
196+
try:
197+
if opersys == "win32":
198+
if lang.lower() == "fr":
199+
locale.setlocale(locale.LC_ALL, "french")
200+
else:
201+
locale.setlocale(locale.LC_ALL, "english")
202+
else:
203+
if lang.lower() == "fr":
204+
locale.setlocale(locale.LC_ALL, str("fr_FR.utf8"))
205+
else:
206+
locale.setlocale(locale.LC_ALL, str("en_GB.utf8"))
207+
except locale.Error as e:
208+
logger.error(
209+
"Selected locale ({}) is not installed: {}".format(lang.lower(), e)
210+
)
211+
logger.debug("Locale set to: {}".format(locale.getlocale()))
212+
213+
self.lang = lang
214+
188215
@classmethod
189216
def convert_octets(self, octets: int) -> str:
190217
"""Convert a mount of octets in readable size.
@@ -325,7 +352,9 @@ def get_request_base_url(self, route: str, prot: str = "https") -> str:
325352
:param str route: route to format
326353
:param str prot: https [DEFAULT] or http
327354
"""
328-
return "{}://{}.isogeo.com/{}/".format(prot, self.api_url, route)
355+
return "{}://{}.isogeo.com/{}/?_lang={}".format(
356+
prot, self.api_url, route, self.lang
357+
)
329358

330359
def get_edit_url(
331360
self,
@@ -443,7 +472,7 @@ def guess_platform_from_url(self, url: str = "https://api.isogeo.com/") -> str:
443472
:param url str: URL string to guess from
444473
445474
:rtype: str
446-
:returns: "prod" or "qa" or "unknown"
475+
:returns: "prod" or "qa" or "unknown"
447476
448477
:Example:
449478

tests/test_conditions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ def test_conditions_listing(self):
173173
self.assertTrue(hasattr(condition, "description"))
174174
self.assertTrue(hasattr(condition, "license"))
175175
# test attributes instances
176-
self.assertIsInstance(condition.license, License)
176+
if "license" in i:
177+
self.assertIsInstance(condition.license, License)
177178
# tests attributes value
178179
self.assertEqual(condition._id, i.get("_id"))
179180
self.assertEqual(condition.description, i.get("description"))

tests/test_shares.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# for whole test
99
python -m unittest tests.test_shares
1010
# for specific
11-
python -m unittest tests.test_shares.TestShares.test_shares_create_basic
11+
python -m unittest tests.test_shares.TestShares.test_shares_create_basic_application
1212
```
1313
"""
1414

@@ -32,7 +32,7 @@
3232

3333

3434
# module target
35-
from isogeo_pysdk import Isogeo, Share, Catalog
35+
from isogeo_pysdk import Isogeo, Share
3636

3737

3838
# #############################################################################

tests/test_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,8 @@ def test_get_request_base_url(self):
212212
"""Test URL request builder."""
213213
resource_url = self.utils.get_request_base_url("resources")
214214
self.assertEqual(
215-
resource_url, "https://{}.isogeo.com/resources/".format(self.utils.api_url)
215+
resource_url,
216+
"https://{}.isogeo.com/resources/?_lang=fr".format(self.utils.api_url),
216217
)
217218

218219
# -- URLs Builders - view on web app -------------------------------------

0 commit comments

Comments
 (0)