app.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. """The main Pynecone app."""
  2. from typing import Any, Callable, Coroutine, Dict, List, Optional, Type, Union
  3. from fastapi import FastAPI
  4. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  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, EventHandler
  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 Socket.IO AsyncServer.
  26. sio: Optional[AsyncServer] = None
  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. # events handlers to trigger when a page load
  36. load_events: Dict[str, EventHandler] = {}
  37. def __init__(self, *args, **kwargs):
  38. """Initialize the app.
  39. Args:
  40. *args: Args to initialize the app with.
  41. **kwargs: Kwargs to initialize the app with.
  42. """
  43. super().__init__(*args, **kwargs)
  44. # Add middleware.
  45. self.middleware.append(HydrateMiddleware())
  46. # Set up the state manager.
  47. self.state_manager.setup(state=self.state)
  48. # Set up the API.
  49. self.api = FastAPI()
  50. # Set up the Socket.IO AsyncServer.
  51. self.sio = AsyncServer(async_mode="asgi", cors_allowed_origins="*")
  52. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  53. socket_app = ASGIApp(self.sio, socketio_path=str(constants.Endpoint.EVENT))
  54. # Create the event namespace and attach the main app. Not related to the path above.
  55. event_namespace = EventNamespace("/event")
  56. event_namespace.app = self
  57. # Register the event namespace with the socket.
  58. self.sio.register_namespace(event_namespace)
  59. # Mount the socket app with the API.
  60. self.api.mount("/", socket_app)
  61. def __repr__(self) -> str:
  62. """Get the string representation of the app.
  63. Returns:
  64. The string representation of the app.
  65. """
  66. return f"<App state={self.state.__name__}>"
  67. def __call__(self) -> FastAPI:
  68. """Run the backend api instance.
  69. Returns:
  70. The backend api.
  71. """
  72. return self.api
  73. def preprocess(self, state: State, event: Event) -> Optional[Delta]:
  74. """Preprocess the event.
  75. This is where middleware can modify the event before it is processed.
  76. Each middleware is called in the order it was added to the app.
  77. If a middleware returns a delta, the event is not processed and the
  78. delta is returned.
  79. Args:
  80. state: The state to preprocess.
  81. event: The event to preprocess.
  82. Returns:
  83. An optional state to return.
  84. """
  85. for middleware in self.middleware:
  86. out = middleware.preprocess(app=self, state=state, event=event)
  87. if out is not None:
  88. return out
  89. def postprocess(self, state: State, event: Event, delta: Delta) -> Optional[Delta]:
  90. """Postprocess the event.
  91. This is where middleware can modify the delta after it is processed.
  92. Each middleware is called in the order it was added to the app.
  93. If a middleware returns a delta, the delta is not processed and the
  94. delta is returned.
  95. Args:
  96. state: The state to postprocess.
  97. event: The event to postprocess.
  98. delta: The delta to postprocess.
  99. Returns:
  100. An optional state to return.
  101. """
  102. for middleware in self.middleware:
  103. out = middleware.postprocess(
  104. app=self, state=state, event=event, delta=delta
  105. )
  106. if out is not None:
  107. return out
  108. def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
  109. """Add middleware to the app.
  110. Args:
  111. middleware: The middleware to add.
  112. index: The index to add the middleware at.
  113. """
  114. if index is None:
  115. self.middleware.append(middleware)
  116. else:
  117. self.middleware.insert(index, middleware)
  118. def add_page(
  119. self,
  120. component: Union[Component, ComponentCallable],
  121. route: Optional[str] = None,
  122. title: str = constants.DEFAULT_TITLE,
  123. description: str = constants.DEFAULT_DESCRIPTION,
  124. image=constants.DEFAULT_IMAGE,
  125. on_load: Optional[EventHandler] = None,
  126. path: Optional[str] = None,
  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: (deprecated) The path to the component.
  134. route: The route 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. on_load: The event handler that will be called each time the page load.
  139. """
  140. if path is not None:
  141. utils.deprecate(
  142. "The `path` argument is deprecated for `add_page`. Use `route` instead."
  143. )
  144. route = path
  145. # If the route is not set, get it from the callable.
  146. if route is None:
  147. assert isinstance(
  148. component, Callable
  149. ), "Route must be set if component is not a callable."
  150. route = component.__name__
  151. # Check if the route given is valid
  152. utils.verify_route_validity(route)
  153. # Apply dynamic args to the route.
  154. self.state.setup_dynamic_args(utils.get_route_args(route))
  155. # Generate the component if it is a callable.
  156. component = component if isinstance(component, Component) else component()
  157. # Add meta information to the component.
  158. compiler_utils.add_meta(
  159. component, title=title, image=image, description=description
  160. )
  161. # Format the route.
  162. route = utils.format_route(route)
  163. # Add the page.
  164. self._check_routes_conflict(route)
  165. self.pages[route] = component
  166. if on_load:
  167. self.load_events[route] = on_load
  168. def _check_routes_conflict(self, new_route: str):
  169. """Verify if there is any conflict between the new route and any existing route.
  170. Based on conflicts that NextJS would throw if not intercepted.
  171. Raises:
  172. ValueError: exception showing which conflict exist with the route to be added
  173. Args:
  174. new_route: the route being newly added.
  175. """
  176. newroute_catchall = utils.catchall_in_route(new_route)
  177. if not newroute_catchall:
  178. return
  179. for route in self.pages:
  180. route = "" if route == "index" else route
  181. if new_route.startswith(f"{route}/[[..."):
  182. raise ValueError(
  183. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  184. )
  185. route_catchall = utils.catchall_in_route(route)
  186. if (
  187. route_catchall
  188. and newroute_catchall
  189. and utils.catchall_prefix(route) == utils.catchall_prefix(new_route)
  190. ):
  191. raise ValueError(
  192. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  193. )
  194. def add_custom_404_page(self, component, title=None, image=None, description=None):
  195. """Define a custom 404 page for any url having no match.
  196. If there is no page defined on 'index' route, add the 404 page to it.
  197. If there is no global catchall defined, add the 404 page with a catchall
  198. Args:
  199. component: The component to display at the page.
  200. title: The title of the page.
  201. description: The description of the page.
  202. image: The image to display on the page.
  203. """
  204. title = title or constants.TITLE_404
  205. image = image or constants.FAVICON_404
  206. description = description or constants.DESCRIPTION_404
  207. component = component if isinstance(component, Component) else component()
  208. compiler_utils.add_meta(
  209. component, title=title, image=image, description=description
  210. )
  211. froute = utils.format_route
  212. if (froute(constants.ROOT_404) not in self.pages) and (
  213. not any(page.startswith("[[...") for page in self.pages)
  214. ):
  215. self.pages[froute(constants.ROOT_404)] = component
  216. if not any(
  217. page.startswith("[...") or page.startswith("[[...") for page in self.pages
  218. ):
  219. self.pages[froute(constants.SLUG_404)] = component
  220. def compile(self, force_compile: bool = False):
  221. """Compile the app and output it to the pages folder.
  222. If the config environment is set to production, the app will
  223. not be compiled.
  224. Args:
  225. force_compile: Whether to force the app to compile.
  226. """
  227. # Get the env mode.
  228. config = utils.get_config()
  229. if config.env != constants.Env.DEV and not force_compile:
  230. print("Skipping compilation in non-dev mode.")
  231. return
  232. # Create the database models.
  233. if config.db_url is not None:
  234. Model.create_all()
  235. # Empty the .web pages directory
  236. compiler.purge_web_pages_dir()
  237. # Compile the root document with base styles and fonts.
  238. compiler.compile_document_root(self.stylesheets)
  239. # Compile the theme.
  240. compiler.compile_theme(self.style)
  241. # Compile the pages.
  242. custom_components = set()
  243. for route, component in self.pages.items():
  244. component.add_style(self.style)
  245. compiler.compile_page(route, component, self.state)
  246. # Add the custom components from the page to the set.
  247. custom_components |= component.get_custom_components()
  248. # Compile the custom components.
  249. compiler.compile_components(custom_components)
  250. async def process(app: App, event: Event) -> StateUpdate:
  251. """Process an event.
  252. Args:
  253. app: The app to process the event for.
  254. event: The event to process.
  255. Returns:
  256. The state update after processing the event.
  257. """
  258. # Get the state for the session.
  259. state = app.state_manager.get_state(event.token)
  260. # pass router_data to the state of the App
  261. state.router_data = event.router_data
  262. # also pass router_data to all substates
  263. for _, substate in state.substates.items():
  264. substate.router_data = event.router_data
  265. state.router_data[constants.RouteVar.CLIENT_TOKEN] = event.token
  266. # Preprocess the event.
  267. pre = app.preprocess(state, event)
  268. if pre is not None:
  269. return StateUpdate(delta=pre)
  270. # Apply the event to the state.
  271. update = await state.process(event)
  272. app.state_manager.set_state(event.token, state)
  273. # Postprocess the event.
  274. post = app.postprocess(state, event, update.delta)
  275. if post is not None:
  276. return StateUpdate(delta=post)
  277. # Return the update.
  278. return update
  279. class EventNamespace(AsyncNamespace):
  280. """The event namespace."""
  281. # The backend API object.
  282. app: App
  283. def on_connect(self, sid, environ):
  284. """Event for when the websocket disconnects.
  285. Args:
  286. sid: The Socket.IO session id.
  287. environ: The request information, including HTTP headers.
  288. """
  289. pass
  290. def on_disconnect(self, sid):
  291. """Event for when the websocket disconnects.
  292. Args:
  293. sid: The Socket.IO session id.
  294. """
  295. pass
  296. async def on_event(self, sid, data):
  297. """Event for receiving front-end websocket events.
  298. Args:
  299. sid: The Socket.IO session id.
  300. data: The event data.
  301. """
  302. # Get the event.
  303. event = Event.parse_raw(data)
  304. # Process the event.
  305. update = await process(self.app, event)
  306. # Emit the event.
  307. await self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  308. async def on_ping(self, sid):
  309. """Event for testing the API endpoint.
  310. Args:
  311. sid: The Socket.IO session id.
  312. """
  313. # Emit the test event.
  314. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)