app.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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_credentials=True,
  72. allow_methods=["*"],
  73. allow_headers=["*"],
  74. )
  75. def preprocess(self, state: State, event: Event) -> Optional[Delta]:
  76. """Preprocess the event.
  77. This is where middleware can modify the event before it is processed.
  78. Each middleware is called in the order it was added to the app.
  79. If a middleware returns a delta, the event is not processed and the
  80. delta is returned.
  81. Args:
  82. state: The state to preprocess.
  83. event: The event to preprocess.
  84. Returns:
  85. An optional state to return.
  86. """
  87. for middleware in self.middleware:
  88. out = middleware.preprocess(app=self, state=state, event=event)
  89. if out is not None:
  90. return out
  91. def postprocess(self, state: State, event: Event, delta: Delta) -> Optional[Delta]:
  92. """Postprocess the event.
  93. This is where middleware can modify the delta after it is processed.
  94. Each middleware is called in the order it was added to the app.
  95. If a middleware returns a delta, the delta is not processed and the
  96. delta is returned.
  97. Args:
  98. state: The state to postprocess.
  99. event: The event to postprocess.
  100. delta: The delta to postprocess.
  101. Returns:
  102. An optional state to return.
  103. """
  104. for middleware in self.middleware:
  105. out = middleware.postprocess(
  106. app=self, state=state, event=event, delta=delta
  107. )
  108. if out is not None:
  109. return out
  110. def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
  111. """Add middleware to the app.
  112. Args:
  113. middleware: The middleware to add.
  114. index: The index to add the middleware at.
  115. """
  116. if index is None:
  117. self.middleware.append(middleware)
  118. else:
  119. self.middleware.insert(index, middleware)
  120. def add_page(
  121. self,
  122. component: Union[Component, ComponentCallable],
  123. path: Optional[str] = None,
  124. title: str = constants.DEFAULT_TITLE,
  125. description: str = constants.DEFAULT_DESCRIPTION,
  126. image=constants.DEFAULT_IMAGE,
  127. ):
  128. """Add a page to the app.
  129. If the component is a callable, by default the route is the name of the
  130. function. Otherwise, a route must be provided.
  131. Args:
  132. component: The component to display at the page.
  133. path: The path to display the component at.
  134. title: The title of the page.
  135. description: The description of the page.
  136. image: The image to display on the page.
  137. """
  138. # If the path is not set, get it from the callable.
  139. if path is None:
  140. assert isinstance(
  141. component, Callable
  142. ), "Path must be set if component is not a callable."
  143. path = component.__name__
  144. # Get args from the path for dynamic routes.
  145. args = utils.get_path_args(path)
  146. # Generate the component if it is a callable.
  147. component = component if isinstance(component, Component) else component(*args)
  148. # Add meta information to the component.
  149. compiler_utils.add_meta(
  150. component, title=title, image=image, description=description
  151. )
  152. # Format the route.
  153. route = utils.format_route(path)
  154. # Add the page.
  155. self.pages[route] = component
  156. def compile(self, force_compile: bool = False):
  157. """Compile the app and output it to the pages folder.
  158. If the config environment is set to production, the app will
  159. not be compiled.
  160. Args:
  161. force_compile: Whether to force the app to compile.
  162. """
  163. # Get the env mode.
  164. config = utils.get_config()
  165. if config.env != constants.Env.DEV and not force_compile:
  166. print("Skipping compilation in non-dev mode.")
  167. return
  168. # Create the database models.
  169. Model.create_all()
  170. # Create the root document with base styles and fonts.
  171. self.pages[constants.DOCUMENT_ROOT] = compiler_utils.create_document_root(
  172. self.stylesheets
  173. )
  174. self.pages[constants.THEME] = compiler_utils.create_theme(self.style) # type: ignore
  175. # Compile the pages.
  176. for path, component in self.pages.items():
  177. self.compile_page(path, component)
  178. def compile_page(
  179. self, path: str, component: Component, write: bool = True
  180. ) -> Tuple[str, str]:
  181. """Compile a single page.
  182. Args:
  183. path: The path to compile the page to.
  184. component: The component to compile.
  185. write: Whether to write the page to the pages folder.
  186. Returns:
  187. The path and code of the compiled page.
  188. """
  189. # Get the path for the output file.
  190. output_path = utils.get_page_path(path)
  191. # Compile the document root.
  192. if path == constants.DOCUMENT_ROOT:
  193. code = compiler.compile_document_root(component)
  194. # Compile the theme.
  195. elif path == constants.THEME:
  196. output_path = utils.get_theme_path()
  197. code = compiler.compile_theme(component) # type: ignore
  198. # Compile all other pages.
  199. else:
  200. # Add the style to the component.
  201. component.add_style(self.style)
  202. code = compiler.compile_component(
  203. component=component,
  204. state=self.state,
  205. )
  206. # Write the page to the pages folder.
  207. if write:
  208. utils.write_page(output_path, code)
  209. return output_path, code
  210. def get_state(self, token: str) -> State:
  211. """Get the state for a token.
  212. Args:
  213. token: The token to get the state for.
  214. Returns:
  215. The state for the token.
  216. """
  217. return self.state_manager.get_state(token)
  218. def set_state(self, token: str, state: State):
  219. """Set the state for a token.
  220. Args:
  221. token: The token to set the state for.
  222. state: The state to set.
  223. """
  224. self.state_manager.set_state(token, state)
  225. async def _ping() -> str:
  226. """Test API endpoint.
  227. Returns:
  228. The response.
  229. """
  230. return "pong"
  231. def _event(app: App):
  232. """Websocket endpoint for events.
  233. Args:
  234. app: The app to add the endpoint to.
  235. Returns:
  236. The websocket endpoint.
  237. """
  238. async def ws(websocket: WebSocket):
  239. """Create websocket endpoint.
  240. Args:
  241. websocket: The websocket sending events.
  242. """
  243. # Accept the connection.
  244. await websocket.accept()
  245. # Process events until the connection is closed.
  246. while True:
  247. # Get the event.
  248. event = Event.parse_raw(await websocket.receive_text())
  249. # Process the event.
  250. update = await process(app, event)
  251. # Send the update.
  252. await websocket.send_text(update.json())
  253. return ws
  254. async def process(app: App, event: Event) -> StateUpdate:
  255. """Process an event.
  256. Args:
  257. app: The app to process the event for.
  258. event: The event to process.
  259. Returns:
  260. The state update after processing the event.
  261. """
  262. # Get the state for the session.
  263. state = app.get_state(event.token)
  264. # Preprocess the event.
  265. pre = app.preprocess(state, event)
  266. if pre is not None:
  267. return StateUpdate(delta=pre)
  268. # Apply the event to the state.
  269. update = await state.process(event)
  270. app.set_state(event.token, state)
  271. # Postprocess the event.
  272. post = app.postprocess(state, event, update.delta)
  273. if post is not None:
  274. return StateUpdate(delta=post)
  275. # Return the update.
  276. return update