app.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. """The main Pynecone app."""
  2. from typing import Any, Callable, Coroutine, Dict, List, Optional, Type, Union
  3. from fastapi import FastAPI, UploadFile
  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, Union[EventHandler, List[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. # To upload files.
  94. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  95. def add_cors(self):
  96. """Add CORS middleware to the app."""
  97. self.api.add_middleware(
  98. cors.CORSMiddleware,
  99. allow_credentials=True,
  100. allow_methods=["*"],
  101. allow_headers=["*"],
  102. allow_origins=["*"],
  103. )
  104. def preprocess(self, state: State, event: Event) -> Optional[Delta]:
  105. """Preprocess the event.
  106. This is where middleware can modify the event before it is processed.
  107. Each middleware is called in the order it was added to the app.
  108. If a middleware returns a delta, the event is not processed and the
  109. delta is returned.
  110. Args:
  111. state: The state to preprocess.
  112. event: The event to preprocess.
  113. Returns:
  114. An optional state to return.
  115. """
  116. for middleware in self.middleware:
  117. out = middleware.preprocess(app=self, state=state, event=event)
  118. if out is not None:
  119. return out
  120. def postprocess(self, state: State, event: Event, delta: Delta) -> Optional[Delta]:
  121. """Postprocess the event.
  122. This is where middleware can modify the delta after it is processed.
  123. Each middleware is called in the order it was added to the app.
  124. If a middleware returns a delta, the delta is not processed and the
  125. delta is returned.
  126. Args:
  127. state: The state to postprocess.
  128. event: The event to postprocess.
  129. delta: The delta to postprocess.
  130. Returns:
  131. An optional state to return.
  132. """
  133. for middleware in self.middleware:
  134. out = middleware.postprocess(
  135. app=self, state=state, event=event, delta=delta
  136. )
  137. if out is not None:
  138. return out
  139. def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
  140. """Add middleware to the app.
  141. Args:
  142. middleware: The middleware to add.
  143. index: The index to add the middleware at.
  144. """
  145. if index is None:
  146. self.middleware.append(middleware)
  147. else:
  148. self.middleware.insert(index, middleware)
  149. def add_page(
  150. self,
  151. component: Union[Component, ComponentCallable],
  152. route: Optional[str] = None,
  153. title: str = constants.DEFAULT_TITLE,
  154. description: str = constants.DEFAULT_DESCRIPTION,
  155. image=constants.DEFAULT_IMAGE,
  156. on_load: Optional[Union[EventHandler, List[EventHandler]]] = None,
  157. path: Optional[str] = None,
  158. meta: List[Dict] = constants.DEFAULT_META_LIST,
  159. ):
  160. """Add a page to the app.
  161. If the component is a callable, by default the route is the name of the
  162. function. Otherwise, a route must be provided.
  163. Args:
  164. component: The component to display at the page.
  165. path: (deprecated) The path to the component.
  166. route: The route to display the component at.
  167. title: The title of the page.
  168. description: The description of the page.
  169. image: The image to display on the page.
  170. on_load: The event handler(s) that will be called each time the page load.
  171. meta: The metadata of the page.
  172. """
  173. if path is not None:
  174. utils.deprecate(
  175. "The `path` argument is deprecated for `add_page`. Use `route` instead."
  176. )
  177. route = path
  178. # If the route is not set, get it from the callable.
  179. if route is None:
  180. assert isinstance(
  181. component, Callable
  182. ), "Route must be set if component is not a callable."
  183. route = component.__name__
  184. # Check if the route given is valid
  185. utils.verify_route_validity(route)
  186. # Apply dynamic args to the route.
  187. self.state.setup_dynamic_args(utils.get_route_args(route))
  188. # Generate the component if it is a callable.
  189. component = component if isinstance(component, Component) else component()
  190. # Add meta information to the component.
  191. compiler_utils.add_meta(
  192. component, title=title, image=image, description=description, meta=meta
  193. )
  194. # Format the route.
  195. route = utils.format_route(route)
  196. # Add the page.
  197. self._check_routes_conflict(route)
  198. self.pages[route] = component
  199. if on_load:
  200. self.load_events[route] = on_load
  201. def _check_routes_conflict(self, new_route: str):
  202. """Verify if there is any conflict between the new route and any existing route.
  203. Based on conflicts that NextJS would throw if not intercepted.
  204. Raises:
  205. ValueError: exception showing which conflict exist with the route to be added
  206. Args:
  207. new_route: the route being newly added.
  208. """
  209. newroute_catchall = utils.catchall_in_route(new_route)
  210. if not newroute_catchall:
  211. return
  212. for route in self.pages:
  213. route = "" if route == "index" else route
  214. if new_route.startswith(f"{route}/[[..."):
  215. raise ValueError(
  216. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  217. )
  218. route_catchall = utils.catchall_in_route(route)
  219. if (
  220. route_catchall
  221. and newroute_catchall
  222. and utils.catchall_prefix(route) == utils.catchall_prefix(new_route)
  223. ):
  224. raise ValueError(
  225. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  226. )
  227. def add_custom_404_page(
  228. self,
  229. component,
  230. title=None,
  231. image=None,
  232. description=None,
  233. meta=constants.DEFAULT_META_LIST,
  234. ):
  235. """Define a custom 404 page for any url having no match.
  236. If there is no page defined on 'index' route, add the 404 page to it.
  237. If there is no global catchall defined, add the 404 page with a catchall
  238. Args:
  239. component: The component to display at the page.
  240. title: The title of the page.
  241. description: The description of the page.
  242. image: The image to display on the page.
  243. meta: The metadata of the page.
  244. """
  245. title = title or constants.TITLE_404
  246. image = image or constants.FAVICON_404
  247. description = description or constants.DESCRIPTION_404
  248. component = component if isinstance(component, Component) else component()
  249. compiler_utils.add_meta(
  250. component, title=title, image=image, description=description, meta=meta
  251. )
  252. froute = utils.format_route
  253. if (froute(constants.ROOT_404) not in self.pages) and (
  254. not any(page.startswith("[[...") for page in self.pages)
  255. ):
  256. self.pages[froute(constants.ROOT_404)] = component
  257. if not any(
  258. page.startswith("[...") or page.startswith("[[...") for page in self.pages
  259. ):
  260. self.pages[froute(constants.SLUG_404)] = component
  261. def compile(self, force_compile: bool = False):
  262. """Compile the app and output it to the pages folder.
  263. If the config environment is set to production, the app will
  264. not be compiled.
  265. Args:
  266. force_compile: Whether to force the app to compile.
  267. """
  268. for render, kwargs in DECORATED_ROUTES:
  269. self.add_page(render, **kwargs)
  270. # Get the env mode.
  271. config = utils.get_config()
  272. if config.env != constants.Env.DEV and not force_compile:
  273. print("Skipping compilation in non-dev mode.")
  274. return
  275. # Update models during hot reload.
  276. if config.db_url is not None:
  277. Model.create_all()
  278. # Empty the .web pages directory
  279. compiler.purge_web_pages_dir()
  280. # Compile the root document with base styles and fonts.
  281. compiler.compile_document_root(self.stylesheets)
  282. # Compile the theme.
  283. compiler.compile_theme(self.style)
  284. # Compile the pages.
  285. custom_components = set()
  286. for route, component in self.pages.items():
  287. component.add_style(self.style)
  288. compiler.compile_page(route, component, self.state)
  289. # Add the custom components from the page to the set.
  290. custom_components |= component.get_custom_components()
  291. # Compile the custom components.
  292. compiler.compile_components(custom_components)
  293. async def process(
  294. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  295. ) -> StateUpdate:
  296. """Process an event.
  297. Args:
  298. app: The app to process the event for.
  299. event: The event to process.
  300. sid: The Socket.IO session id.
  301. headers: The client headers.
  302. client_ip: The client_ip.
  303. Returns:
  304. The state update after processing the event.
  305. """
  306. # Get the state for the session.
  307. state = app.state_manager.get_state(event.token)
  308. formatted_params = utils.format_query_params(event.router_data)
  309. # Pass router_data to the state of the App.
  310. state.router_data = event.router_data
  311. # also pass router_data to all substates
  312. for _, substate in state.substates.items():
  313. substate.router_data = event.router_data
  314. state.router_data[constants.RouteVar.QUERY] = formatted_params
  315. state.router_data[constants.RouteVar.CLIENT_TOKEN] = event.token
  316. state.router_data[constants.RouteVar.SESSION_ID] = sid
  317. state.router_data[constants.RouteVar.HEADERS] = headers
  318. state.router_data[constants.RouteVar.CLIENT_IP] = client_ip
  319. # Preprocess the event.
  320. pre = app.preprocess(state, event)
  321. if pre is not None:
  322. return StateUpdate(delta=pre)
  323. # Apply the event to the state.
  324. update = await state.process(event)
  325. app.state_manager.set_state(event.token, state)
  326. # Postprocess the event.
  327. post = app.postprocess(state, event, update.delta)
  328. if post is not None:
  329. return StateUpdate(delta=post)
  330. # Return the update.
  331. return update
  332. async def ping() -> str:
  333. """Test API endpoint.
  334. Returns:
  335. The response.
  336. """
  337. return "pong"
  338. def upload(app: App):
  339. """Upload a file.
  340. Args:
  341. app: The app to upload the file for.
  342. Returns:
  343. The upload function.
  344. """
  345. async def upload_file(file: UploadFile):
  346. """Upload a file.
  347. Args:
  348. file: The file to upload.
  349. Returns:
  350. The state update after processing the event.
  351. """
  352. # Get the token and filename.
  353. token, handler, filename = file.filename.split(":", 2)
  354. file.filename = filename
  355. # Get the state for the session.
  356. state = app.state_manager.get_state(token)
  357. event = Event(token=token, name=handler, payload={"file": file})
  358. update = await state.process(event)
  359. return update
  360. return upload_file
  361. class EventNamespace(AsyncNamespace):
  362. """The event namespace."""
  363. # The application object.
  364. app: App
  365. def __init__(self, namespace: str, app: App):
  366. """Initialize the event namespace.
  367. Args:
  368. namespace: The namespace.
  369. app: The application object.
  370. """
  371. super().__init__(namespace)
  372. self.app = app
  373. def on_connect(self, sid, environ):
  374. """Event for when the websocket disconnects.
  375. Args:
  376. sid: The Socket.IO session id.
  377. environ: The request information, including HTTP headers.
  378. """
  379. pass
  380. def on_disconnect(self, sid):
  381. """Event for when the websocket disconnects.
  382. Args:
  383. sid: The Socket.IO session id.
  384. """
  385. pass
  386. async def on_event(self, sid, data):
  387. """Event for receiving front-end websocket events.
  388. Args:
  389. sid: The Socket.IO session id.
  390. data: The event data.
  391. """
  392. # Get the event.
  393. event = Event.parse_raw(data)
  394. # Get the event environment.
  395. assert self.app.sio is not None
  396. environ = self.app.sio.get_environ(sid, self.namespace)
  397. # Get the client headers.
  398. headers = {
  399. k.decode("utf-8"): v.decode("utf-8")
  400. for (k, v) in environ["asgi.scope"]["headers"]
  401. }
  402. # Get the client IP
  403. client_ip = environ["REMOTE_ADDR"]
  404. # Process the event.
  405. update = await process(self.app, event, sid, headers, client_ip)
  406. # Emit the event.
  407. await self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid)
  408. async def on_ping(self, sid):
  409. """Event for testing the API endpoint.
  410. Args:
  411. sid: The Socket.IO session id.
  412. """
  413. # Emit the test event.
  414. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)