From d4f150509a38bd534d18a6bfe0a4c9528fef9eb4 Mon Sep 17 00:00:00 2001 From: Mark W <32108590+zenon18@users.noreply.github.com> Date: Tue, 21 May 2024 14:11:48 -0400 Subject: [PATCH] moved eval query functionality to a function in utils --- python/nrel/routee/compass/compass_app.py | 19 +++-------- python/nrel/routee/compass/io/utils.py | 41 ++++++++++++++++++++++- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/python/nrel/routee/compass/compass_app.py b/python/nrel/routee/compass/compass_app.py index f9c55df6..e72a67ce 100644 --- a/python/nrel/routee/compass/compass_app.py +++ b/python/nrel/routee/compass/compass_app.py @@ -8,6 +8,7 @@ from nrel.routee.compass.routee_compass_py import ( CompassAppWrapper, ) +from nrel.routee.compass.io.utils import eval_query import toml @@ -169,20 +170,10 @@ def run_in_batches( # attempt to read a line and see if we can eval it line = line.strip() query_str += line - if query_str[0] == "[": - query_str = query_str[1:] - if query_str == "": - continue - try: - if query_str[-1] in [",", "]"]: - query = eval(query_str[:-1]) - else: - query = eval(query_str) - except SyntaxError: - continue - - queries.append(query) - query_str = "" + query = eval_query(query_str) + if query is not None: + queries.append(query) + query_str = "" if queries: yield self.run(queries) diff --git a/python/nrel/routee/compass/io/utils.py b/python/nrel/routee/compass/io/utils.py index bfa8d17f..cf66e9f8 100644 --- a/python/nrel/routee/compass/io/utils.py +++ b/python/nrel/routee/compass/io/utils.py @@ -6,11 +6,14 @@ import math import itertools import logging -from typing import Union +from typing import Union, Dict, Any log = logging.getLogger(__name__) +Query = Dict[str, Any] + + class TileResolution(Enum): ONE_ARC_SECOND = 1 ONE_THIRD_ARC_SECOND = 13 @@ -170,3 +173,39 @@ def add_grade_to_graph( g = ox.add_edge_grades(g) return g + + +def eval_query(query_str: str) -> Union[Query | None]: + """ + Takes a query json string and parses it as a query + + Args: + + query_str: The query as a json string + + Returns: + + A query dictionary if the string can be parsed, or None if it + cannot be parsed + + Example: + >>> query_str = '{"origin_name": "NREL", "destination_name": '\ + '"Comrade Brewing Company", "origin_x": '\ + '-105.1710052, "origin_y": 39.7402804, '\ + '"destination_x": '-104.9009913, "destination_y": '\ + '39.6757025}' + >>> query = eval_query(query_str) + """ + if query_str[0] == "[": + query_str = query_str[1:] + if query_str == "": + return None + try: + if query_str[-1] in [",", "]"]: + query = eval(query_str[:-1]) + else: + query = eval(query_str) + except SyntaxError: + return None + + return query