Skip to content

Commit

Permalink
Factor out code for dynamic routes (reflex-dev#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
picklelo committed Dec 15, 2022
1 parent 933c367 commit e127149
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 18 deletions.
18 changes: 3 additions & 15 deletions pynecone/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,25 +209,13 @@ def add_page(
), "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
)
Expand Down
46 changes: 43 additions & 3 deletions pynecone/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit e127149

Please sign in to comment.