From e127149bc12da7e1f18103eeb180b153298432d8 Mon Sep 17 00:00:00 2001 From: Nikhil Rao Date: Thu, 15 Dec 2022 11:37:39 -0800 Subject: [PATCH] Factor out code for dynamic routes (#109) --- pynecone/app.py | 18 +++--------------- pynecone/utils.py | 46 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 18 deletions(-) diff --git a/pynecone/app.py b/pynecone/app.py index c53349451..1447a6031 100644 --- a/pynecone/app.py +++ b/pynecone/app.py @@ -209,25 +209,13 @@ class App(Base): ), "Path must be set if component is not a callable." path = component.__name__ - from pynecone.var import BaseVar - - parts = os.path.split(path) - check = re.compile(r"^\[(.+)\]$") - args = [] - for part in parts: - match = check.match(part) - if match: - v = BaseVar( - name=match.groups()[0], - type_=str, - state=f"{constants.ROUTER}.query", - ) - args.append(v) + # Get args from the path for dynamic routes. + args = utils.get_path_args(path) # Generate the component if it is a callable. component = component if isinstance(component, Component) else component(*args) - # Add the title to the component. + # Add meta information to the component. compiler_utils.add_meta( component, title=title, image=image, description=description ) diff --git a/pynecone/utils.py b/pynecone/utils.py index 65c8f0afa..e34afba8f 100644 --- a/pynecone/utils.py +++ b/pynecone/utils.py @@ -303,11 +303,21 @@ def get_bun_path() -> str: Returns: The path to the bun executable. + + Raises: + FileNotFoundError: If bun or npm is not installed. """ - # On windows, we use npm instead of bun. + # On Windows, we use npm instead of bun. if platform.system() == "Windows": - return str(which("npm")) - return os.path.expandvars(get_config().bun_path) + if which("npm") is None: + raise FileNotFoundError("Pynecone requires npm to be installed on Windows.") + return "npm" + + # On other platforms, we use bun. + bun_path = os.path.expandvars(get_config().bun_path) + if which(bun_path) is None: + raise FileNotFoundError("Pynecone requires bun to be installed.") + return bun_path def get_app() -> ModuleType: @@ -681,6 +691,36 @@ def get_theme_path() -> str: return os.path.join(constants.WEB_UTILS_DIR, constants.THEME + constants.JS_EXT) +def get_path_args(path: str) -> List[str]: + """Get the path arguments for the given path. + + Args: + path: The path to get the arguments for. + + Returns: + The path arguments. + """ + # Import here to avoid circular imports. + from pynecone.var import BaseVar + + # Regex to check for path args. + check = re.compile(r"^\[(.+)\]$") + + # Iterate over the path parts and check for path args. + args = [] + for part in os.path.split(path): + match = check.match(part) + if match: + # Add the path arg to the list. + v = BaseVar( + name=match.groups()[0], + type_=str, + state=f"{constants.ROUTER}.query", + ) + args.append(v) + return args + + def write_page(path: str, code: str): """Write the given code to the given path.