app.py 16 KB

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