Skip to content

Commit

Permalink
Merge branch 'main' into 120-removing-blue-lines-in-ors-tool
Browse files Browse the repository at this point in the history
  • Loading branch information
koebi authored Dec 6, 2023
2 parents 2916443 + bdb7974 commit 3573380
Show file tree
Hide file tree
Showing 40 changed files with 945 additions and 762 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: Ruff
on: [ push, pull_request ]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: chartboost/ruff-action@v1
with:
src: ORStools
args: format --check
- uses: chartboost/ruff-action@v1
with:
src: ORStools
args: check
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ RELEASING:

### Added
- remove blue lines every time the red X button is clicked ([#120](https://github.com/GIScience/orstools-qgis-plugin/issues/120))
- Additional parameter for the "smoothing factor" to isochrones processing algorithms ([#172](https://github.com/GIScience/orstools-qgis-plugin/issues/172))
- Mention omission of configuration options when using traveling salesman

## [1.6.0] - 2023-07-25

### Added
- translation mechanism ([#183](https://github.com/GIScience/orstools-qgis-plugin/pull/183))
- german translation ([#183](https://github.com/GIScience/orstools-qgis-plugin/pull/183))


## [1.5.3] - 2023-03-30

### Fixed
Expand Down
10 changes: 4 additions & 6 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,14 @@ def __init__(self, iface):
self.plugin_dir = os.path.dirname(__file__)

# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'orstools_{}.qm'.format(locale))
locale = QSettings().value("locale/userLocale")[0:2]
locale_path = os.path.join(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__}"
50 changes: 28 additions & 22 deletions ORStools/common/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,31 @@
"""

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",
"INPUT_SMOOTHING",
]
93 changes: 41 additions & 52 deletions ORStools/common/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,33 +57,29 @@ 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.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 +120,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 +137,20 @@ 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,7 +159,6 @@ def request(self,
self._check_status()

except exceptions.OverQueryLimit as e:

# Let the instances know something happened
# noinspection PyUnresolvedReferences
self.overQueryLimit.emit()
Expand All @@ -176,17 +167,21 @@ def request(self,
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 +197,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 All @@ -245,7 +234,7 @@ def _generate_auth_url(self, path, params):
:rtype: string
"""

if type(params) is dict:
if isinstance(params, dict):
params = sorted(dict(**params).items())

# Only auto-add API key when using ORS. If own instance, API key must
Expand Down
Loading

0 comments on commit 3573380

Please sign in to comment.