Add pc.route decorator (#513)

This commit is contained in:
Thomas Brandého 2023-02-12 18:37:47 +01:00 committed by GitHub
parent 094082c35b
commit c203ad57a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 62 additions and 2 deletions

View File

@ -13,6 +13,7 @@ from .constants import Env, Transports
from .event import EventChain, console_log, redirect, window_alert
from .middleware import Middleware
from .model import Model, session
from .route import route
from .state import ComputedVar as var
from .state import State
from .style import toggle_color_mode

View File

@ -12,6 +12,7 @@ from pynecone.compiler import utils as compiler_utils
from pynecone.components.component import Component, ComponentStyle
from pynecone.event import Event, EventHandler
from pynecone.middleware import HydrateMiddleware, Middleware
from pynecone.route import DECORATED_ROUTES
from pynecone.state import DefaultState, Delta, State, StateManager, StateUpdate
# Define custom types.
@ -306,6 +307,9 @@ class App(Base):
Args:
force_compile: Whether to force the app to compile.
"""
for render, kwargs in DECORATED_ROUTES:
self.add_page(render, **kwargs)
# Get the env mode.
config = utils.get_config()
if config.env != constants.Env.DEV and not force_compile:

54
pynecone/route.py Normal file
View File

@ -0,0 +1,54 @@
"""The route decorator and associated variables."""
from typing import Optional
from pynecone.event import EventHandler
DECORATED_ROUTES = []
def route(
route: Optional[str] = None,
title: Optional[str] = None,
image: Optional[str] = None,
description: Optional[str] = None,
on_load: Optional[EventHandler] = None,
):
"""Decorate a function as a page.
pc.App() will automatically call add_page() for any method decorated with route
when App.compile is called.
All defaults are None because they will use the one from add_page().
Note: the decorated functions still need to be imported.
Args:
route: The route to reach the page. Defaults to None.
title: The title of the page. Defaults to None.
image: The favicon of the page. Defaults to None.
description: The description of the page. Defaults to None.
on_load: The event handler called when the page load. Defaults to None.
Returns:
The decorated function.
"""
def decorator(render_fn):
kwargs = {}
if route:
kwargs["route"] = route
if title:
kwargs["title"] = title
if image:
kwargs["image"] = image
if description:
kwargs["description"] = description
if on_load:
kwargs["on_load"] = on_load
DECORATED_ROUTES.append((render_fn, kwargs))
return render_fn
return decorator

View File

@ -716,8 +716,9 @@ def change_or_terminate_port(port, _type) -> str:
def setup_backend():
"""Sets up backend. Specifically ensures backend
database is updated when running --no-frontend.
"""Set up backend.
Specifically ensures backend database is updated when running --no-frontend.
"""
config = get_config()
if config.db_url is not None: