Skip to content

Commit

Permalink
Automatically set the locale matching the selected API language (#93)
Browse files Browse the repository at this point in the history
* add a method to set locale from the selected lang - close #91
* minor fixes before release
* housekeeping dependencies
  • Loading branch information
Guts committed Aug 26, 2019
1 parent 63f5411 commit 7042816
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 72 deletions.
58 changes: 29 additions & 29 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions isogeo_pysdk/api/routes_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __init__(self, api_client=None):
def listing(
self,
workgroup_id: str = None,
include: list = ["_abilities"],
include: list = ("_abilities"),
caching: bool = 1,
) -> list:
"""Get all applications which are accessible by the authenticated user OR applications for a workgroup.
Expand Down Expand Up @@ -178,7 +178,7 @@ def create(
if check_exists == 1:
# retrieve workgroup applications
if not self.api_client._applications_names:
self.applications(include=[])
self.listing(include=())
# check
if application.name in self.api_client._applications_names:
logger.debug(
Expand Down
2 changes: 1 addition & 1 deletion isogeo_pysdk/api/routes_condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
# submodules
from isogeo_pysdk.checker import IsogeoChecker
from isogeo_pysdk.decorators import ApiDecorators
from isogeo_pysdk.models import Condition, Metadata, License
from isogeo_pysdk.models import Condition, Metadata
from isogeo_pysdk.utils import IsogeoUtils

# #############################################################################
Expand Down
8 changes: 5 additions & 3 deletions isogeo_pysdk/api/routes_share.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,12 +246,14 @@ def exists(self, share_id: str) -> bool:
else:
pass

# URL builder
url_share_exists = "{}{}".format(utils.get_request_base_url("shares"), share_id)
# URL
url_share_exists = utils.get_request_base_url(
route="shares/{}".format(share_id)
)

# request
req_share_exists = self.api_client.get(
url_share_exists,
url=url_share_exists,
headers=self.api_client.header,
proxies=self.api_client.proxies,
verify=self.api_client.ssl,
Expand Down
30 changes: 4 additions & 26 deletions isogeo_pysdk/isogeo.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
# ##################################

# Standard library
import locale
import logging
from sys import platform as opersys

# 3rd party library
from oauthlib.oauth2 import BackendApplicationClient, LegacyApplicationClient
Expand Down Expand Up @@ -63,7 +61,7 @@ class Isogeo(OAuth2Session):
:param str auth_mode: oAuth2 authentication flow to use. Must be one of 'AUTH_MODES'
:param str platform: to request production or quality assurance
:param dict proxy: dictionary of proxy settings as described in `Requests <https://2.python-requests.org/en/master/user/advanced/#proxies>`_
:param str lang: API localization ("en" or "fr").
:param str lang: API localization ("en" or "fr"). Defaults to 'fr'.
:param str app_name: to custom the application name and user-agent
Expand Down Expand Up @@ -101,7 +99,7 @@ class Isogeo(OAuth2Session):
auto_refresh_url="{}/oauth/token".format(environ.get("ISOGEO_ID_URL")),
platform=environ.get("ISOGEO_PLATFORM", "qa"),
)
# getting a token
isogeo.connect()
Expand Down Expand Up @@ -210,30 +208,12 @@ def __init__(
# setting language
if lang.lower() not in ("fr", "en"):
logger.warning(
"Isogeo API is only available in English ('en', "
"default) or French ('fr'). "
"Language has been set on English."
"Isogeo API is only available in English ('en', default) or French ('fr'). Language has been set on English."
)
self.lang = "en"
else:
self.lang = lang.lower()

# setting locale according to the language passed
# try:
# if opersys == "win32":
# if lang.lower() == "fr":
# locale.setlocale(locale.LC_ALL, str("fra_fra"))
# else:
# locale.setlocale(locale.LC_ALL, str("uk_UK"))
# else:
# if lang.lower() == "fr":
# locale.setlocale(locale.LC_ALL, str("fr_FR.utf8"))
# else:
# locale.setlocale(locale.LC_ALL, str("en_GB.utf8"))
# except locale.Error as e:
# logger.error(
# "Selected locale ({}) is not installed: {}".format(lang.lower(), e)
# )
utils.set_lang_and_locale(self.lang)

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

from isogeo_pysdk.models import Keyword, Share

# ------------ Log & debug ----------------
logger = logging.getLogger()
logging.captureWarnings(True)
Expand Down
43 changes: 36 additions & 7 deletions isogeo_pysdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# Standard library
import base64
import json
import locale
import logging
import math
import quopri
Expand All @@ -23,6 +24,7 @@
from configparser import ConfigParser
from datetime import datetime
from pathlib import Path
from sys import platform as opersys
from urllib.parse import urlparse

# 3rd party
Expand Down Expand Up @@ -133,6 +135,8 @@ class IsogeoUtils(object):
},
}

lang = "fr"

def __init__(self, proxies: dict = dict()):
"""Instanciate IsogeoUtils module.
Expand All @@ -158,14 +162,9 @@ def set_base_url(self, platform: str = "prod"):
self.platform = platform
if platform == "prod":
self.ssl = True
logger.debug("Using production platform.")
elif platform == "qa":
self.ssl = False
logger.debug("Using Quality Assurance platform (reduced perfs).")
else:
logging.error(
"Platform must be one of: {}".format(" | ".join(self.API_URLS.keys()))
)
raise ValueError(
3,
"Platform must be one of: {}".format(" | ".join(self.API_URLS.keys())),
Expand All @@ -185,6 +184,34 @@ def set_base_url(self, platform: str = "prod"):
self.ssl,
)

@classmethod
def set_lang_and_locale(self, lang: str):
"""Set requests language and the matching locale.
:param str lang: language code to set API localization ("en" or "fr"). Defaults to 'fr'.
"""
lang = lang.lower()

# setting locale according to the language passed and depending on OS
try:
if opersys == "win32":
if lang.lower() == "fr":
locale.setlocale(locale.LC_ALL, "french")
else:
locale.setlocale(locale.LC_ALL, "english")
else:
if lang.lower() == "fr":
locale.setlocale(locale.LC_ALL, str("fr_FR.utf8"))
else:
locale.setlocale(locale.LC_ALL, str("en_GB.utf8"))
except locale.Error as e:
logger.error(
"Selected locale ({}) is not installed: {}".format(lang.lower(), e)
)
logger.debug("Locale set to: {}".format(locale.getlocale()))

self.lang = lang

@classmethod
def convert_octets(self, octets: int) -> str:
"""Convert a mount of octets in readable size.
Expand Down Expand Up @@ -325,7 +352,9 @@ def get_request_base_url(self, route: str, prot: str = "https") -> str:
:param str route: route to format
:param str prot: https [DEFAULT] or http
"""
return "{}://{}.isogeo.com/{}/".format(prot, self.api_url, route)
return "{}://{}.isogeo.com/{}/?_lang={}".format(
prot, self.api_url, route, self.lang
)

def get_edit_url(
self,
Expand Down Expand Up @@ -443,7 +472,7 @@ def guess_platform_from_url(self, url: str = "https://api.isogeo.com/") -> str:
:param url str: URL string to guess from
:rtype: str
:returns: "prod" or "qa" or "unknown"
:returns: "prod" or "qa" or "unknown"
:Example:
Expand Down
3 changes: 2 additions & 1 deletion tests/test_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ def test_conditions_listing(self):
self.assertTrue(hasattr(condition, "description"))
self.assertTrue(hasattr(condition, "license"))
# test attributes instances
self.assertIsInstance(condition.license, License)
if "license" in i:
self.assertIsInstance(condition.license, License)
# tests attributes value
self.assertEqual(condition._id, i.get("_id"))
self.assertEqual(condition.description, i.get("description"))
Expand Down
4 changes: 2 additions & 2 deletions tests/test_shares.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# for whole test
python -m unittest tests.test_shares
# for specific
python -m unittest tests.test_shares.TestShares.test_shares_create_basic
python -m unittest tests.test_shares.TestShares.test_shares_create_basic_application
```
"""

Expand All @@ -32,7 +32,7 @@


# module target
from isogeo_pysdk import Isogeo, Share, Catalog
from isogeo_pysdk import Isogeo, Share


# #############################################################################
Expand Down
3 changes: 2 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ def test_get_request_base_url(self):
"""Test URL request builder."""
resource_url = self.utils.get_request_base_url("resources")
self.assertEqual(
resource_url, "https://{}.isogeo.com/resources/".format(self.utils.api_url)
resource_url,
"https://{}.isogeo.com/resources/?_lang=fr".format(self.utils.api_url),
)

# -- URLs Builders - view on web app -------------------------------------
Expand Down

0 comments on commit 7042816

Please sign in to comment.