app.py 11 KB

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