app.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. """The main Pynecone app."""
  2. from typing import Any, Callable, Coroutine, Dict, List, Optional, 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. # Check if the path given is valid
  146. utils.verify_path_validity(path)
  147. self.state.setup_dynamic_args(utils.get_path_args(path))
  148. # Generate the component if it is a callable.
  149. component = component if isinstance(component, Component) else component()
  150. # Add meta information to the component.
  151. compiler_utils.add_meta(
  152. component, title=title, image=image, description=description
  153. )
  154. # Format the route.
  155. route = utils.format_route(path)
  156. # Add the page.
  157. self._check_routes_conflict(route)
  158. self.pages[route] = component
  159. def _check_routes_conflict(self, new_route: str):
  160. """Verify if there is any conflict between the new route and any existing route.
  161. Based on conflicts that NextJS would throw if not intercepted.
  162. Raises:
  163. ValueError: exception showing which conflict exist with the path to be added
  164. Args:
  165. new_route: the route being newly added.
  166. """
  167. newroute_catchall = utils.catchall_in_route(new_route)
  168. if not newroute_catchall:
  169. return
  170. for route in self.pages:
  171. route = "" if route == "index" else route
  172. if new_route.startswith(route + "/[[..."):
  173. raise ValueError(
  174. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  175. )
  176. route_catchall = utils.catchall_in_route(route)
  177. if route_catchall and newroute_catchall:
  178. # both route have a catchall, check if preceding path is the same
  179. if utils.catchall_prefix(route) == utils.catchall_prefix(new_route):
  180. raise ValueError(
  181. f"You cannot use multiple catchall for the same dynamic path ({route} !== {new_route})"
  182. )
  183. def compile(self, force_compile: bool = False):
  184. """Compile the app and output it to the pages folder.
  185. If the config environment is set to production, the app will
  186. not be compiled.
  187. Args:
  188. force_compile: Whether to force the app to compile.
  189. """
  190. # Get the env mode.
  191. config = utils.get_config()
  192. if config.env != constants.Env.DEV and not force_compile:
  193. print("Skipping compilation in non-dev mode.")
  194. return
  195. # Create the database models.
  196. Model.create_all()
  197. # Compile the root document with base styles and fonts.
  198. compiler.compile_document_root(self.stylesheets)
  199. # Compile the theme.
  200. compiler.compile_theme(self.style)
  201. # Compile the pages.
  202. custom_components = set()
  203. for path, component in self.pages.items():
  204. component.add_style(self.style)
  205. compiler.compile_page(path, component, self.state)
  206. # Add the custom components from the page to the set.
  207. custom_components |= component.get_custom_components()
  208. # Compile the custom components.
  209. compiler.compile_components(custom_components)
  210. async def ping() -> str:
  211. """Test API endpoint.
  212. Returns:
  213. The response.
  214. """
  215. return "pong"
  216. def event(app: App):
  217. """Websocket endpoint for events.
  218. Args:
  219. app: The app to add the endpoint to.
  220. Returns:
  221. The websocket endpoint.
  222. """
  223. async def ws(websocket: WebSocket):
  224. """Create websocket endpoint.
  225. Args:
  226. websocket: The websocket sending events.
  227. """
  228. # Accept the connection.
  229. await websocket.accept()
  230. # Process events until the connection is closed.
  231. while True:
  232. # Get the event.
  233. try:
  234. event = Event.parse_raw(await websocket.receive_text())
  235. except WebSocketDisconnect:
  236. # Close the connection.
  237. return
  238. # Process the event.
  239. update = await process(app, event)
  240. # Send the update.
  241. await websocket.send_text(update.json())
  242. return ws
  243. async def process(app: App, event: Event) -> StateUpdate:
  244. """Process an event.
  245. Args:
  246. app: The app to process the event for.
  247. event: The event to process.
  248. Returns:
  249. The state update after processing the event.
  250. """
  251. # Get the state for the session.
  252. state = app.state_manager.get_state(event.token)
  253. state.router_data = event.router_data
  254. # Preprocess the event.
  255. pre = app.preprocess(state, event)
  256. if pre is not None:
  257. return StateUpdate(delta=pre)
  258. # Apply the event to the state.
  259. update = await state.process(event)
  260. app.state_manager.set_state(event.token, state)
  261. # Postprocess the event.
  262. post = app.postprocess(state, event, update.delta)
  263. if post is not None:
  264. return StateUpdate(delta=post)
  265. # Return the update.
  266. return update