app.py 19 KB

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