app.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """The main Pynecone app."""
  2. import os
  3. import re
  4. from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Type, Union
  5. import fastapi
  6. from fastapi.middleware import cors
  7. from pynecone import constants, utils
  8. from pynecone.base import Base
  9. from pynecone.compiler import compiler
  10. from pynecone.compiler import utils as compiler_utils
  11. from pynecone.components.component import Component, ComponentStyle
  12. from pynecone.event import Event
  13. from pynecone.middleware import HydrateMiddleware, Middleware
  14. from pynecone.model import Model
  15. from pynecone.state import DefaultState, Delta, State, StateManager, StateUpdate
  16. # Define custom types.
  17. ComponentCallable = Callable[[], Component]
  18. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  19. class App(Base):
  20. """A Pynecone application."""
  21. # A map from a page route to the component to render.
  22. pages: Dict[str, Component] = {}
  23. # A list of URLs to stylesheets to include in the app.
  24. stylesheets: List[str] = []
  25. # The backend API object.
  26. api: fastapi.FastAPI = None # type: ignore
  27. # The state class to use for the app.
  28. state: Type[State] = DefaultState
  29. # Class to manage many client states.
  30. state_manager: StateManager = StateManager()
  31. # The styling to apply to each component.
  32. style: ComponentStyle = {}
  33. # Middleware to add to the app.
  34. middleware: List[Middleware] = []
  35. def __init__(self, *args, **kwargs):
  36. """Initialize the app.
  37. Args:
  38. *args: Args to initialize the app with.
  39. **kwargs: Kwargs to initialize the app with.
  40. """
  41. super().__init__(*args, **kwargs)
  42. # Add middleware.
  43. self.middleware.append(HydrateMiddleware())
  44. # Set up the state manager.
  45. self.state_manager.setup(state=self.state)
  46. # Set up the API.
  47. self.api = fastapi.FastAPI()
  48. self.add_cors()
  49. self.add_default_endpoints()
  50. def __repr__(self) -> str:
  51. """Get the string representation of the app.
  52. Returns:
  53. The string representation of the app.
  54. """
  55. return f"<App state={self.state.__name__}>"
  56. def add_default_endpoints(self):
  57. """Add the default endpoints."""
  58. # To test the server.
  59. self.get(str(constants.Endpoint.PING))(_ping)
  60. # To make state changes.
  61. self.post(str(constants.Endpoint.EVENT))(_event(app=self))
  62. def add_cors(self):
  63. """Add CORS middleware to the app."""
  64. self.api.add_middleware(
  65. cors.CORSMiddleware,
  66. allow_origins=["*"],
  67. allow_methods=["*"],
  68. allow_headers=["*"],
  69. )
  70. def get(self, path: str, *args, **kwargs) -> Callable:
  71. """Register a get request.
  72. Args:
  73. path: The endpoint path to link to the request.
  74. *args: Args to pass to the request.
  75. **kwargs: Kwargs to pass to the request.
  76. Returns:
  77. A decorator to handle the request.
  78. """
  79. return self.api.get(path, *args, **kwargs)
  80. def post(self, path: str, *args, **kwargs) -> Callable:
  81. """Register a post request.
  82. Args:
  83. path: The endpoint path to link to the request.
  84. *args: Args to pass to the request.
  85. **kwargs: Kwargs to pass to the request.
  86. Returns:
  87. A decorator to handle the request.
  88. """
  89. return self.api.post(path, *args, **kwargs)
  90. def preprocess(self, state: State, event: Event) -> Optional[Delta]:
  91. """Preprocess the event.
  92. This is where middleware can modify the event before it is processed.
  93. Each middleware is called in the order it was added to the app.
  94. If a middleware returns a delta, the event is not processed and the
  95. delta is returned.
  96. Args:
  97. state: The state to preprocess.
  98. event: The event to preprocess.
  99. Returns:
  100. An optional state to return.
  101. """
  102. for middleware in self.middleware:
  103. out = middleware.preprocess(app=self, state=state, event=event)
  104. if out is not None:
  105. return out
  106. def postprocess(self, state: State, event: Event, delta: Delta) -> Optional[Delta]:
  107. """Postprocess the event.
  108. This is where middleware can modify the delta after it is processed.
  109. Each middleware is called in the order it was added to the app.
  110. If a middleware returns a delta, the delta is not processed and the
  111. delta is returned.
  112. Args:
  113. state: The state to postprocess.
  114. event: The event to postprocess.
  115. delta: The delta to postprocess.
  116. Returns:
  117. An optional state to return.
  118. """
  119. for middleware in self.middleware:
  120. out = middleware.postprocess(
  121. app=self, state=state, event=event, delta=delta
  122. )
  123. if out is not None:
  124. return out
  125. def add_page(
  126. self,
  127. component: Union[Component, ComponentCallable],
  128. path: Optional[str] = None,
  129. title: str = constants.DEFAULT_TITLE,
  130. ):
  131. """Add a page to the app.
  132. If the component is a callable, by default the route is the name of the
  133. function. Otherwise, a route must be provided.
  134. Args:
  135. component: The component to display at the page.
  136. path: The path to display the component at.
  137. title: The title of the page.
  138. """
  139. # If the path is not set, get it from the callable.
  140. if path is None:
  141. assert isinstance(
  142. component, Callable
  143. ), "Path must be set if component is not a callable."
  144. path = component.__name__
  145. from pynecone.var import BaseVar
  146. parts = os.path.split(path)
  147. check = re.compile(r"^\[(.+)\]$")
  148. args = []
  149. for part in parts:
  150. match = check.match(part)
  151. if match:
  152. v = BaseVar(
  153. name=match.groups()[0],
  154. type_=str,
  155. state=f"{constants.ROUTER}.query",
  156. )
  157. args.append(v)
  158. # Generate the component if it is a callable.
  159. component = component if isinstance(component, Component) else component(*args)
  160. # Add the title to the component.
  161. compiler_utils.add_title(component, title)
  162. # Format the route.
  163. route = utils.format_route(path)
  164. # Add the page.
  165. self.pages[route] = component
  166. def compile(self, ignore_env: bool = False):
  167. """Compile the app and output it to the pages folder.
  168. If the config environment is set to production, the app will
  169. not be compiled.
  170. Args:
  171. ignore_env: Whether to ignore the config environment.
  172. """
  173. # Get the env mode.
  174. config = utils.get_config()
  175. if not ignore_env and config.env != constants.Env.DEV:
  176. print("Skipping compilation in non-dev mode.")
  177. return
  178. # Create the database models.
  179. Model.create_all()
  180. # Create the root document with base styles and fonts.
  181. self.pages[constants.DOCUMENT_ROOT] = compiler_utils.create_document_root(
  182. self.stylesheets
  183. )
  184. self.pages[constants.THEME] = compiler_utils.create_theme(self.style) # type: ignore
  185. # Compile the pages.
  186. for path, component in self.pages.items():
  187. path, code = self.compile_page(path, component)
  188. def compile_page(
  189. self, path: str, component: Component, write: bool = True
  190. ) -> Tuple[str, str]:
  191. """Compile a single page.
  192. Args:
  193. path: The path to compile the page to.
  194. component: The component to compile.
  195. write: Whether to write the page to the pages folder.
  196. Returns:
  197. The path and code of the compiled page.
  198. """
  199. # Get the path for the output file.
  200. output_path = utils.get_page_path(path)
  201. # Compile the document root.
  202. if path == constants.DOCUMENT_ROOT:
  203. code = compiler.compile_document_root(component)
  204. # Compile the theme.
  205. elif path == constants.THEME:
  206. output_path = utils.get_theme_path()
  207. code = compiler.compile_theme(component) # type: ignore
  208. # Compile all other pages.
  209. else:
  210. # Add the style to the component.
  211. component.add_style(self.style)
  212. code = compiler.compile_component(
  213. component=component,
  214. state=self.state,
  215. )
  216. # Write the page to the pages folder.
  217. if write:
  218. utils.write_page(output_path, code)
  219. return output_path, code
  220. def get_state(self, token: str) -> State:
  221. """Get the state for a token.
  222. Args:
  223. token: The token to get the state for.
  224. Returns:
  225. The state for the token.
  226. """
  227. return self.state_manager.get_state(token)
  228. def set_state(self, token: str, state: State):
  229. """Set the state for a token.
  230. Args:
  231. token: The token to set the state for.
  232. state: The state to set.
  233. """
  234. self.state_manager.set_state(token, state)
  235. async def _ping() -> str:
  236. """Test API endpoint.
  237. Returns:
  238. The response.
  239. """
  240. return "pong"
  241. def _event(app: App) -> Reducer:
  242. """Create an event reducer to modify the state.
  243. Args:
  244. app: The app to modify the state of.
  245. Returns:
  246. A handler that takes in an event and modifies the state.
  247. """
  248. async def process(event: Event) -> StateUpdate:
  249. # Get the state for the session.
  250. state = app.get_state(event.token)
  251. # Preprocess the event.
  252. pre = app.preprocess(state, event)
  253. if pre is not None:
  254. return StateUpdate(delta=pre)
  255. # Apply the event to the state.
  256. update = await state.process(event)
  257. app.set_state(event.token, state)
  258. # Postprocess the event.
  259. post = app.postprocess(state, event, update.delta)
  260. if post is not None:
  261. return StateUpdate(delta=post)
  262. # Return the delta.
  263. return update
  264. return process