app.py 23 KB

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