app.py 20 KB

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