app.py 15 KB

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