Skip to content

Commit

Permalink
style: ruff formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
koebi committed Nov 23, 2023
1 parent 0d11360 commit bb87a1b
Show file tree
Hide file tree
Showing 26 changed files with 1,065 additions and 772 deletions.
10 changes: 5 additions & 5 deletions ORStools/ORStoolsPlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

class ORStools:
"""QGIS Plugin Implementation."""

# noinspection PyTypeChecker,PyArgumentList,PyCallByClass

def __init__(self, iface):
Expand All @@ -54,17 +55,16 @@ def __init__(self, iface):
self.plugin_dir = os.path.dirname(__file__)

# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale = QSettings().value("locale/userLocale")[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'orstools_{}.qm'.format(locale))
self.plugin_dir, "i18n", "orstools_{}.qm".format(locale)
)

if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)

if qVersion() > '4.3.3':
if qVersion() > "4.3.3":
QCoreApplication.installTranslator(self.translator)

def initGui(self):
Expand Down
26 changes: 13 additions & 13 deletions ORStools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,28 @@ def classFactory(iface): # pylint: disable=invalid-name
"""

from .ORStoolsPlugin import ORStools

return ORStools(iface)


# Define plugin wide constants
PLUGIN_NAME = 'ORS Tools'
DEFAULT_COLOR = '#a8b1f5'
PLUGIN_NAME = "ORS Tools"
DEFAULT_COLOR = "#a8b1f5"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

RESOURCE_PREFIX = ":plugins/ORStools/img/"
CONFIG_PATH = os.path.join(BASE_DIR, 'config.yml')
ENV_VARS = {'ORS_REMAINING': 'X-Ratelimit-Remaining',
'ORS_QUOTA': 'X-Ratelimit-Limit'}
CONFIG_PATH = os.path.join(BASE_DIR, "config.yml")
ENV_VARS = {"ORS_REMAINING": "X-Ratelimit-Remaining", "ORS_QUOTA": "X-Ratelimit-Limit"}

# Read metadata.txt
METADATA = configparser.ConfigParser()
METADATA.read(os.path.join(BASE_DIR, 'metadata.txt'), encoding='utf-8')
METADATA.read(os.path.join(BASE_DIR, "metadata.txt"), encoding="utf-8")
today = datetime.today()

__version__ = METADATA['general']['version']
__author__ = METADATA['general']['author']
__email__ = METADATA['general']['email']
__web__ = METADATA['general']['homepage']
__help__ = METADATA['general']['help']
__date__ = today.strftime('%Y-%m-%d')
__copyright__ = f'(C) {today.year} by {__author__}'
__version__ = METADATA["general"]["version"]
__author__ = METADATA["general"]["author"]
__email__ = METADATA["general"]["email"]
__web__ = METADATA["general"]["homepage"]
__help__ = METADATA["general"]["help"]
__date__ = today.strftime("%Y-%m-%d")
__copyright__ = f"(C) {today.year} by {__author__}"
54 changes: 32 additions & 22 deletions ORStools/common/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,35 @@
"""

PROFILES = [
'driving-car',
'driving-hgv',
'cycling-regular',
'cycling-road',
'cycling-mountain',
'cycling-electric',
'foot-walking',
'foot-hiking',
'wheelchair'
]

DIMENSIONS = ['time', 'distance']

PREFERENCES = ['fastest', 'shortest', 'recommended']

OPTIMIZATION_MODES = ['Round Trip', 'Fix Start Point', 'Fix End Point', 'Fix Start and End Point']

AVOID_FEATURES = ['highways', 'tollways', 'ferries', 'fords', 'steps']

AVOID_BORDERS = ['all', 'controlled', 'none']

ADVANCED_PARAMETERS = ["INPUT_AVOID_FEATURES", "INPUT_AVOID_BORDERS", "INPUT_AVOID_COUNTRIES", "INPUT_AVOID_POLYGONS"]
"driving-car",
"driving-hgv",
"cycling-regular",
"cycling-road",
"cycling-mountain",
"cycling-electric",
"foot-walking",
"foot-hiking",
"wheelchair",
]

DIMENSIONS = ["time", "distance"]

PREFERENCES = ["fastest", "shortest", "recommended"]

OPTIMIZATION_MODES = [
"Round Trip",
"Fix Start Point",
"Fix End Point",
"Fix Start and End Point",
]

AVOID_FEATURES = ["highways", "tollways", "ferries", "fords", "steps"]

AVOID_BORDERS = ["all", "controlled", "none"]

ADVANCED_PARAMETERS = [
"INPUT_AVOID_FEATURES",
"INPUT_AVOID_BORDERS",
"INPUT_AVOID_COUNTRIES",
"INPUT_AVOID_POLYGONS",
]
106 changes: 53 additions & 53 deletions ORStools/common/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,33 +57,33 @@ def __init__(self, provider=None):
"""
QObject.__init__(self)

self.key = provider['key']
self.base_url = provider['base_url']
self.ENV_VARS = provider.get('ENV_VARS')
self.key = provider["key"]
self.base_url = provider["base_url"]
self.ENV_VARS = provider.get("ENV_VARS")

# self.session = requests.Session()
retry_timeout = provider.get('timeout')
retry_timeout = provider.get("timeout")

self.nam = networkaccessmanager.NetworkAccessManager(debug=False, timeout=retry_timeout)
self.nam = networkaccessmanager.NetworkAccessManager(
debug=False, timeout=retry_timeout
)

self.retry_timeout = timedelta(seconds=retry_timeout)
self.headers = {
"User-Agent": _USER_AGENT,
'Content-type': 'application/json',
'Authorization': provider['key']
}
"User-Agent": _USER_AGENT,
"Content-type": "application/json",
"Authorization": provider["key"],
}

# Save some references to retrieve in client instances
self.url = None
self.warnings = None

overQueryLimit = pyqtSignal()
def request(self,
url,
params,
first_request_time=None,
retry_counter=0,
post_json=None):

def request(
self, url, params, first_request_time=None, retry_counter=0, post_json=None
):
"""Performs HTTP GET/POST with credentials, returning the body as
JSON.
Expand Down Expand Up @@ -124,14 +124,15 @@ def request(self,
# 0.5 * (1.5 ^ i) is an increased sleep time of 1.5x per iteration,
# starting at 0.5s when retry_counter=1. The first retry will occur
# at 1, so subtract that first.
delay_seconds = 1.5**(retry_counter - 1)
delay_seconds = 1.5 ** (retry_counter - 1)

# Jitter this value by 50% and pause.
time.sleep(delay_seconds * (random.random() + 0.5))

authed_url = self._generate_auth_url(url,
params,
)
authed_url = self._generate_auth_url(
url,
params,
)
self.url = self.base_url + authed_url

# Default to the client-level self.requests_kwargs, with method-level
Expand All @@ -140,25 +141,24 @@ def request(self,

# Determine GET/POST
# requests_method = self.session.get
requests_method = 'GET'
requests_method = "GET"
body = None
if post_json is not None:
# requests_method = self.session.post
# final_requests_kwargs["json"] = post_json
body = post_json
requests_method = 'POST'
requests_method = "POST"

logger.log(
f"url: {self.url}\nParameters: {json.dumps(body, indent=2)}",
0
)
logger.log(f"url: {self.url}\nParameters: {json.dumps(body, indent=2)}", 0)

try:
response, content = self.nam.request(self.url,
method=requests_method,
body=body,
headers=self.headers,
blocking=True)
response, content = self.nam.request(
self.url,
method=requests_method,
body=body,
headers=self.headers,
blocking=True,
)
except networkaccessmanager.RequestsExceptionTimeout:
raise exceptions.Timeout

Expand All @@ -167,26 +167,32 @@ def request(self,
self._check_status()

except exceptions.OverQueryLimit as e:

# Let the instances know something happened
# noinspection PyUnresolvedReferences
self.overQueryLimit.emit()
logger.log(f"{e.__class__.__name__}: {str(e)}", 1)

return self.request(url, params, first_request_time, retry_counter + 1, post_json)
return self.request(
url, params, first_request_time, retry_counter + 1, post_json
)

except exceptions.ApiError as e:
logger.log(f"Feature ID {post_json['id']} caused a {e.__class__.__name__}: {str(e)}", 2)
logger.log(
f"Feature ID {post_json['id']} caused a {e.__class__.__name__}: {str(e)}",
2,
)
raise

raise

# Write env variables if successful
if self.ENV_VARS:
for env_var in self.ENV_VARS:
configmanager.write_env_var(env_var, response.headers.get(self.ENV_VARS[env_var], 'None'))
configmanager.write_env_var(
env_var, response.headers.get(self.ENV_VARS[env_var], "None")
)

return json.loads(content.decode('utf-8'))
return json.loads(content.decode("utf-8"))

def _check_status(self):
"""
Expand All @@ -202,34 +208,28 @@ def _check_status(self):
"""

status_code = self.nam.http_call_result.status_code
message = self.nam.http_call_result.text if self.nam.http_call_result.text != '' else self.nam.http_call_result.reason
message = (
self.nam.http_call_result.text
if self.nam.http_call_result.text != ""
else self.nam.http_call_result.reason
)

if not status_code:
raise Exception(f"{message}. Are your provider settings correct and the provider ready?")
raise Exception(
f"{message}. Are your provider settings correct and the provider ready?"
)

elif status_code == 403:
raise exceptions.InvalidKey(
str(status_code),
message
)
raise exceptions.InvalidKey(str(status_code), message)

elif status_code == 429:
raise exceptions.OverQueryLimit(
str(status_code),
message
)
raise exceptions.OverQueryLimit(str(status_code), message)
# Internal error message for Bad Request
elif 400 <= status_code < 500:
raise exceptions.ApiError(
str(status_code),
message
)
raise exceptions.ApiError(str(status_code), message)
# Other HTTP errors have different formatting
elif status_code != 200:
raise exceptions.GenericServerError(
str(status_code),
message
)
raise exceptions.GenericServerError(str(status_code), message)

def _generate_auth_url(self, path, params):
"""Returns the path and query string portion of the request URL, first
Expand Down
Loading

0 comments on commit bb87a1b

Please sign in to comment.