app.py 21 KB

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