app.py 10 KB

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