app.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. """The main Pynecone app."""
  2. import asyncio
  3. import inspect
  4. from typing import (
  5. Any,
  6. AsyncIterator,
  7. Callable,
  8. Coroutine,
  9. Dict,
  10. List,
  11. Optional,
  12. Tuple,
  13. Type,
  14. Union,
  15. )
  16. from fastapi import FastAPI, UploadFile
  17. from fastapi.middleware import cors
  18. from socketio import ASGIApp, AsyncNamespace, AsyncServer
  19. from starlette_admin.contrib.sqla.admin import Admin
  20. from starlette_admin.contrib.sqla.view import ModelView
  21. from pynecone import constants
  22. from pynecone.admin import AdminDash
  23. from pynecone.base import Base
  24. from pynecone.compiler import compiler
  25. from pynecone.compiler import utils as compiler_utils
  26. from pynecone.components.component import Component, ComponentStyle
  27. from pynecone.components.layout.fragment import Fragment
  28. from pynecone.config import get_config
  29. from pynecone.event import Event, EventHandler, EventSpec
  30. from pynecone.middleware import HydrateMiddleware, Middleware
  31. from pynecone.model import Model
  32. from pynecone.route import (
  33. DECORATED_ROUTES,
  34. catchall_in_route,
  35. catchall_prefix,
  36. get_route_args,
  37. verify_route_validity,
  38. )
  39. from pynecone.state import DefaultState, State, StateManager, StateUpdate
  40. from pynecone.utils import format, types
  41. # Define custom types.
  42. ComponentCallable = Callable[[], Component]
  43. Reducer = Callable[[Event], Coroutine[Any, Any, StateUpdate]]
  44. class App(Base):
  45. """A Pynecone application."""
  46. # A map from a page route to the component to render.
  47. pages: Dict[str, Component] = {}
  48. # A list of URLs to stylesheets to include in the app.
  49. stylesheets: List[str] = []
  50. # The backend API object.
  51. api: FastAPI = None # type: ignore
  52. # The Socket.IO AsyncServer.
  53. sio: Optional[AsyncServer] = None
  54. # The socket app.
  55. socket_app: Optional[ASGIApp] = None
  56. # The state class to use for the app.
  57. state: Type[State] = DefaultState
  58. # Class to manage many client states.
  59. state_manager: StateManager = StateManager()
  60. # The styling to apply to each component.
  61. style: ComponentStyle = {}
  62. # Middleware to add to the app.
  63. middleware: List[Middleware] = []
  64. # List of event handlers to trigger when a page loads.
  65. load_events: Dict[str, List[Union[EventHandler, EventSpec]]] = {}
  66. # Admin dashboard
  67. admin_dash: Optional[AdminDash] = None
  68. # The component to render if there is a connection error to the server.
  69. connect_error_component: Optional[Component] = None
  70. def __init__(self, *args, **kwargs):
  71. """Initialize the app.
  72. Args:
  73. *args: Args to initialize the app with.
  74. **kwargs: Kwargs to initialize the app with.
  75. """
  76. super().__init__(*args, **kwargs)
  77. # Get the config
  78. config = get_config()
  79. # Add middleware.
  80. self.middleware.append(HydrateMiddleware())
  81. # Set up the state manager.
  82. self.state_manager.setup(state=self.state)
  83. # Set up the API.
  84. self.api = FastAPI()
  85. self.add_cors()
  86. self.add_default_endpoints()
  87. # Set up the Socket.IO AsyncServer.
  88. self.sio = AsyncServer(
  89. async_mode="asgi",
  90. cors_allowed_origins="*"
  91. if config.cors_allowed_origins == constants.CORS_ALLOWED_ORIGINS
  92. else config.cors_allowed_origins,
  93. cors_credentials=config.cors_credentials,
  94. max_http_buffer_size=config.polling_max_http_buffer_size,
  95. ping_interval=constants.PING_INTERVAL,
  96. ping_timeout=constants.PING_TIMEOUT,
  97. )
  98. # Create the socket app. Note event endpoint constant replaces the default 'socket.io' path.
  99. self.socket_app = ASGIApp(self.sio, socketio_path="")
  100. # Create the event namespace and attach the main app. Not related to any paths.
  101. event_namespace = EventNamespace("/event", self)
  102. # Register the event namespace with the socket.
  103. self.sio.register_namespace(event_namespace)
  104. # Mount the socket app with the API.
  105. self.api.mount(str(constants.Endpoint.EVENT), self.socket_app)
  106. # Set up the admin dash.
  107. self.setup_admin_dash()
  108. def __repr__(self) -> str:
  109. """Get the string representation of the app.
  110. Returns:
  111. The string representation of the app.
  112. """
  113. return f"<App state={self.state.__name__}>"
  114. def __call__(self) -> FastAPI:
  115. """Run the backend api instance.
  116. Returns:
  117. The backend api.
  118. """
  119. return self.api
  120. def add_default_endpoints(self):
  121. """Add the default endpoints."""
  122. # To test the server.
  123. self.api.get(str(constants.Endpoint.PING))(ping)
  124. # To upload files.
  125. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self))
  126. def add_cors(self):
  127. """Add CORS middleware to the app."""
  128. self.api.add_middleware(
  129. cors.CORSMiddleware,
  130. allow_credentials=True,
  131. allow_methods=["*"],
  132. allow_headers=["*"],
  133. allow_origins=["*"],
  134. )
  135. async def preprocess(self, state: State, event: Event) -> Optional[StateUpdate]:
  136. """Preprocess the event.
  137. This is where middleware can modify the event before it is processed.
  138. Each middleware is called in the order it was added to the app.
  139. If a middleware returns an update, the event is not processed and the
  140. update is returned.
  141. Args:
  142. state: The state to preprocess.
  143. event: The event to preprocess.
  144. Returns:
  145. An optional state to return.
  146. """
  147. for middleware in self.middleware:
  148. if asyncio.iscoroutinefunction(middleware.preprocess):
  149. out = await middleware.preprocess(app=self, state=state, event=event)
  150. else:
  151. out = middleware.preprocess(app=self, state=state, event=event)
  152. if out is not None:
  153. return out # type: ignore
  154. async def postprocess(
  155. self, state: State, event: Event, update: StateUpdate
  156. ) -> StateUpdate:
  157. """Postprocess the event.
  158. This is where middleware can modify the delta after it is processed.
  159. Each middleware is called in the order it was added to the app.
  160. Args:
  161. state: The state to postprocess.
  162. event: The event to postprocess.
  163. update: The current state update.
  164. Returns:
  165. The state update to return.
  166. """
  167. for middleware in self.middleware:
  168. if asyncio.iscoroutinefunction(middleware.postprocess):
  169. out = await middleware.postprocess(
  170. app=self, state=state, event=event, update=update
  171. )
  172. else:
  173. out = middleware.postprocess(
  174. app=self, state=state, event=event, update=update
  175. )
  176. if out is not None:
  177. return out # type: ignore
  178. return update
  179. def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
  180. """Add middleware to the app.
  181. Args:
  182. middleware: The middleware to add.
  183. index: The index to add the middleware at.
  184. """
  185. if index is None:
  186. self.middleware.append(middleware)
  187. else:
  188. self.middleware.insert(index, middleware)
  189. def add_page(
  190. self,
  191. component: Union[Component, ComponentCallable],
  192. route: Optional[str] = None,
  193. title: str = constants.DEFAULT_TITLE,
  194. description: str = constants.DEFAULT_DESCRIPTION,
  195. image=constants.DEFAULT_IMAGE,
  196. on_load: Optional[
  197. Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]]]
  198. ] = None,
  199. meta: List[Dict] = constants.DEFAULT_META_LIST,
  200. script_tags: Optional[List[Component]] = None,
  201. ):
  202. """Add a page to the app.
  203. If the component is a callable, by default the route is the name of the
  204. function. Otherwise, a route must be provided.
  205. Args:
  206. component: The component to display at the page.
  207. route: The route to display the component at.
  208. title: The title of the page.
  209. description: The description of the page.
  210. image: The image to display on the page.
  211. on_load: The event handler(s) that will be called each time the page load.
  212. meta: The metadata of the page.
  213. script_tags: List of script tags to be added to component
  214. Raises:
  215. TypeError: If an invalid var operation is used.
  216. """
  217. # If the route is not set, get it from the callable.
  218. if route is None:
  219. assert isinstance(
  220. component, Callable
  221. ), "Route must be set if component is not a callable."
  222. route = component.__name__
  223. # Check if the route given is valid
  224. verify_route_validity(route)
  225. # Apply dynamic args to the route.
  226. self.state.setup_dynamic_args(get_route_args(route))
  227. # Generate the component if it is a callable.
  228. try:
  229. component = component if isinstance(component, Component) else component()
  230. except TypeError as e:
  231. message = str(e)
  232. if "BaseVar" in message or "ComputedVar" in message:
  233. raise TypeError(
  234. "You may be trying to use an invalid Python function on a state var. "
  235. "When referencing a var inside your render code, only limited var operations are supported. "
  236. "See the var operation docs here: https://pynecone.io/docs/state/vars "
  237. ) from e
  238. raise e
  239. # Wrap the component in a fragment.
  240. component = Fragment.create(component)
  241. # Add meta information to the component.
  242. compiler_utils.add_meta(
  243. component, title=title, image=image, description=description, meta=meta
  244. )
  245. # Add script tags if given
  246. if script_tags:
  247. component.children.extend(script_tags)
  248. # Format the route.
  249. route = format.format_route(route)
  250. # Add the page.
  251. self._check_routes_conflict(route)
  252. self.pages[route] = component
  253. # Add the load events.
  254. if on_load:
  255. if not isinstance(on_load, list):
  256. on_load = [on_load]
  257. self.load_events[route] = on_load
  258. def get_load_events(self, route: str) -> List[Union[EventHandler, EventSpec]]:
  259. """Get the load events for a route.
  260. Args:
  261. route: The route to get the load events for.
  262. Returns:
  263. The load events for the route.
  264. """
  265. route = route.lstrip("/")
  266. if route == "":
  267. route = constants.INDEX_ROUTE
  268. return self.load_events.get(route, [])
  269. def _check_routes_conflict(self, new_route: str):
  270. """Verify if there is any conflict between the new route and any existing route.
  271. Based on conflicts that NextJS would throw if not intercepted.
  272. Raises:
  273. ValueError: exception showing which conflict exist with the route to be added
  274. Args:
  275. new_route: the route being newly added.
  276. """
  277. newroute_catchall = catchall_in_route(new_route)
  278. if not newroute_catchall:
  279. return
  280. for route in self.pages:
  281. route = "" if route == "index" else route
  282. if new_route.startswith(f"{route}/[[..."):
  283. raise ValueError(
  284. f"You cannot define a route with the same specificity as a optional catch-all route ('{route}' and '{new_route}')"
  285. )
  286. route_catchall = catchall_in_route(route)
  287. if (
  288. route_catchall
  289. and newroute_catchall
  290. and catchall_prefix(route) == catchall_prefix(new_route)
  291. ):
  292. raise ValueError(
  293. f"You cannot use multiple catchall for the same dynamic route ({route} !== {new_route})"
  294. )
  295. def add_custom_404_page(
  296. self,
  297. component,
  298. title=None,
  299. image=None,
  300. description=None,
  301. meta=constants.DEFAULT_META_LIST,
  302. ):
  303. """Define a custom 404 page for any url having no match.
  304. If there is no page defined on 'index' route, add the 404 page to it.
  305. If there is no global catchall defined, add the 404 page with a catchall
  306. Args:
  307. component: The component to display at the page.
  308. title: The title of the page.
  309. description: The description of the page.
  310. image: The image to display on the page.
  311. meta: The metadata of the page.
  312. """
  313. title = title or constants.TITLE_404
  314. image = image or constants.FAVICON_404
  315. description = description or constants.DESCRIPTION_404
  316. component = component if isinstance(component, Component) else component()
  317. compiler_utils.add_meta(
  318. component, title=title, image=image, description=description, meta=meta
  319. )
  320. froute = format.format_route
  321. if (froute(constants.ROOT_404) not in self.pages) and (
  322. not any(page.startswith("[[...") for page in self.pages)
  323. ):
  324. self.pages[froute(constants.ROOT_404)] = component
  325. if not any(
  326. page.startswith("[...") or page.startswith("[[...") for page in self.pages
  327. ):
  328. self.pages[froute(constants.SLUG_404)] = component
  329. def setup_admin_dash(self):
  330. """Setup the admin dash."""
  331. # Get the config.
  332. config = get_config()
  333. if config.enable_admin and config.admin_dash and config.admin_dash.models:
  334. # Build the admin dashboard
  335. admin = (
  336. config.admin_dash.admin
  337. if config.admin_dash.admin
  338. else Admin(
  339. engine=Model.get_db_engine(),
  340. title="Pynecone Admin Dashboard",
  341. logo_url="https://pynecone.io/logo.png",
  342. )
  343. )
  344. for model in config.admin_dash.models:
  345. admin.add_view(ModelView(model))
  346. admin.mount_to(self.api)
  347. def compile(self):
  348. """Compile the app and output it to the pages folder."""
  349. for render, kwargs in DECORATED_ROUTES:
  350. self.add_page(render, **kwargs)
  351. # Get the env mode.
  352. config = get_config()
  353. # Update models during hot reload.
  354. if config.db_url is not None:
  355. Model.create_all()
  356. # Empty the .web pages directory
  357. compiler.purge_web_pages_dir()
  358. # Compile the root document with base styles and fonts.
  359. compiler.compile_document_root(self.stylesheets)
  360. # Compile the theme.
  361. compiler.compile_theme(self.style)
  362. # Compile the pages.
  363. custom_components = set()
  364. for route, component in self.pages.items():
  365. component.add_style(self.style)
  366. compiler.compile_page(
  367. route,
  368. component,
  369. self.state,
  370. self.connect_error_component,
  371. )
  372. # Add the custom components from the page to the set.
  373. custom_components |= component.get_custom_components()
  374. # Compile the custom components.
  375. compiler.compile_components(custom_components)
  376. async def process(
  377. app: App, event: Event, sid: str, headers: Dict, client_ip: str
  378. ) -> AsyncIterator[StateUpdate]:
  379. """Process an event.
  380. Args:
  381. app: The app to process the event for.
  382. event: The event to process.
  383. sid: The Socket.IO session id.
  384. headers: The client headers.
  385. client_ip: The client_ip.
  386. Yields:
  387. The state updates after processing the event.
  388. """
  389. # Get the state for the session.
  390. state = app.state_manager.get_state(event.token)
  391. # Add request data to the state.
  392. router_data = event.router_data
  393. router_data.update(
  394. {
  395. constants.RouteVar.QUERY: format.format_query_params(event.router_data),
  396. constants.RouteVar.CLIENT_TOKEN: event.token,
  397. constants.RouteVar.SESSION_ID: sid,
  398. constants.RouteVar.HEADERS: headers,
  399. constants.RouteVar.CLIENT_IP: client_ip,
  400. }
  401. )
  402. # re-assign only when the value is different
  403. if state.router_data != router_data:
  404. # assignment will recurse into substates and force recalculation of
  405. # dependent ComputedVar (dynamic route variables)
  406. state.router_data = router_data
  407. # Preprocess the event.
  408. update = await app.preprocess(state, event)
  409. # If there was an update, yield it.
  410. if update is not None:
  411. yield update
  412. # Only process the event if there is no update.
  413. else:
  414. # Process the event.
  415. async for update in state._process(event):
  416. # Postprocess the event.
  417. update = await app.postprocess(state, event, update)
  418. # Yield the update.
  419. yield update
  420. # Set the state for the session.
  421. app.state_manager.set_state(event.token, state)
  422. async def ping() -> str:
  423. """Test API endpoint.
  424. Returns:
  425. The response.
  426. """
  427. return "pong"
  428. def upload(app: App):
  429. """Upload a file.
  430. Args:
  431. app: The app to upload the file for.
  432. Returns:
  433. The upload function.
  434. """
  435. async def upload_file(files: List[UploadFile]):
  436. """Upload a file.
  437. Args:
  438. files: The file(s) to upload.
  439. Returns:
  440. The state update after processing the event.
  441. Raises:
  442. ValueError: if there are no args with supported annotation.
  443. """
  444. assert files[0].filename is not None
  445. token, handler = files[0].filename.split(":")[:2]
  446. for file in files:
  447. assert file.filename is not None
  448. file.filename = file.filename.split(":")[-1]
  449. # Get the state for the session.
  450. state = app.state_manager.get_state(token)
  451. # get the current state(parent state/substate)
  452. path = handler.split(".")[:-1]
  453. current_state = state.get_substate(path)
  454. handler_upload_param: Tuple = ()
  455. # get handler function
  456. func = getattr(current_state, handler.split(".")[-1])
  457. # check if there exists any handler args with annotation, List[UploadFile]
  458. for k, v in inspect.getfullargspec(
  459. func.fn if isinstance(func, EventHandler) else func
  460. ).annotations.items():
  461. if types.is_generic_alias(v) and types._issubclass(
  462. v.__args__[0], UploadFile
  463. ):
  464. handler_upload_param = (k, v)
  465. break
  466. if not handler_upload_param:
  467. raise ValueError(
  468. f"`{handler}` handler should have a parameter annotated as List["
  469. f"pc.UploadFile]"
  470. )
  471. event = Event(
  472. token=token,
  473. name=handler,
  474. payload={handler_upload_param[0]: files},
  475. )
  476. # TODO: refactor this to handle yields.
  477. update = await state._process(event).__anext__()
  478. return update
  479. return upload_file
  480. class EventNamespace(AsyncNamespace):
  481. """The event namespace."""
  482. # The application object.
  483. app: App
  484. def __init__(self, namespace: str, app: App):
  485. """Initialize the event namespace.
  486. Args:
  487. namespace: The namespace.
  488. app: The application object.
  489. """
  490. super().__init__(namespace)
  491. self.app = app
  492. def on_connect(self, sid, environ):
  493. """Event for when the websocket disconnects.
  494. Args:
  495. sid: The Socket.IO session id.
  496. environ: The request information, including HTTP headers.
  497. """
  498. pass
  499. def on_disconnect(self, sid):
  500. """Event for when the websocket disconnects.
  501. Args:
  502. sid: The Socket.IO session id.
  503. """
  504. pass
  505. async def on_event(self, sid, data):
  506. """Event for receiving front-end websocket events.
  507. Args:
  508. sid: The Socket.IO session id.
  509. data: The event data.
  510. """
  511. # Get the event.
  512. event = Event.parse_raw(data)
  513. # Get the event environment.
  514. assert self.app.sio is not None
  515. environ = self.app.sio.get_environ(sid, self.namespace)
  516. assert environ is not None
  517. # Get the client headers.
  518. headers = {
  519. k.decode("utf-8"): v.decode("utf-8")
  520. for (k, v) in environ["asgi.scope"]["headers"]
  521. }
  522. # Get the client IP
  523. client_ip = environ["REMOTE_ADDR"]
  524. # Process the events.
  525. async for update in process(self.app, event, sid, headers, client_ip):
  526. # Emit the event.
  527. await self.emit(str(constants.SocketEvent.EVENT), update.json(), to=sid) # type: ignore
  528. async def on_ping(self, sid):
  529. """Event for testing the API endpoint.
  530. Args:
  531. sid: The Socket.IO session id.
  532. """
  533. # Emit the test event.
  534. await self.emit(str(constants.SocketEvent.PING), "pong", to=sid)