app.py 19 KB

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