utils.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. """General utility functions."""
  2. from __future__ import annotations
  3. import inspect
  4. import json
  5. import os
  6. import platform
  7. import random
  8. import re
  9. import shutil
  10. import signal
  11. import string
  12. import subprocess
  13. import sys
  14. from collections import defaultdict
  15. from subprocess import PIPE
  16. from types import ModuleType
  17. from typing import _GenericAlias # type: ignore
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Callable,
  22. Dict,
  23. List,
  24. Optional,
  25. Tuple,
  26. Type,
  27. Union,
  28. )
  29. import plotly.graph_objects as go
  30. import typer
  31. from plotly.io import to_json
  32. from redis import Redis
  33. from rich.console import Console
  34. from pynecone import constants
  35. from pynecone.base import Base
  36. if TYPE_CHECKING:
  37. from pynecone.app import App
  38. from pynecone.components.component import ImportDict
  39. from pynecone.config import Config
  40. from pynecone.event import Event, EventHandler, EventSpec
  41. from pynecone.var import Var
  42. # Shorthand for join.
  43. join = os.linesep.join
  44. # Console for pretty printing.
  45. console = Console()
  46. # Union of generic types.
  47. GenericType = Union[Type, _GenericAlias]
  48. # Valid state var types.
  49. PrimitiveType = Union[int, float, bool, str, list, dict, tuple]
  50. StateVar = Union[PrimitiveType, Base, None]
  51. def get_args(alias: _GenericAlias) -> Tuple[Type, ...]:
  52. """Get the arguments of a type alias.
  53. Args:
  54. alias: The type alias.
  55. Returns:
  56. The arguments of the type alias.
  57. """
  58. return alias.__args__
  59. def is_generic_alias(cls: GenericType) -> bool:
  60. """Check whether the class is a generic alias.
  61. Args:
  62. cls: The class to check.
  63. Returns:
  64. Whether the class is a generic alias.
  65. """
  66. # For older versions of Python.
  67. if isinstance(cls, _GenericAlias):
  68. return True
  69. try:
  70. from typing import _SpecialGenericAlias # type: ignore
  71. if isinstance(cls, _SpecialGenericAlias):
  72. return True
  73. except ImportError:
  74. pass
  75. # For newer versions of Python.
  76. try:
  77. from types import GenericAlias # type: ignore
  78. return isinstance(cls, GenericAlias)
  79. except ImportError:
  80. return False
  81. def is_union(cls: GenericType) -> bool:
  82. """Check if a class is a Union.
  83. Args:
  84. cls: The class to check.
  85. Returns:
  86. Whether the class is a Union.
  87. """
  88. try:
  89. from typing import _UnionGenericAlias # type: ignore
  90. return isinstance(cls, _UnionGenericAlias)
  91. except ImportError:
  92. pass
  93. if is_generic_alias(cls):
  94. return cls.__origin__ == Union
  95. return False
  96. def get_base_class(cls: GenericType) -> Type:
  97. """Get the base class of a class.
  98. Args:
  99. cls: The class.
  100. Returns:
  101. The base class of the class.
  102. """
  103. if is_union(cls):
  104. return tuple(get_base_class(arg) for arg in get_args(cls))
  105. if is_generic_alias(cls):
  106. return get_base_class(cls.__origin__)
  107. return cls
  108. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  109. """Check if a class is a subclass of another class.
  110. Args:
  111. cls: The class to check.
  112. cls_check: The class to check against.
  113. Returns:
  114. Whether the class is a subclass of the other class.
  115. """
  116. # Special check for Any.
  117. if cls_check == Any:
  118. return True
  119. if cls == Any or cls == Callable:
  120. return False
  121. cls_base = get_base_class(cls)
  122. cls_check_base = get_base_class(cls_check)
  123. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  124. def _isinstance(obj: Any, cls: GenericType) -> bool:
  125. """Check if an object is an instance of a class.
  126. Args:
  127. obj: The object to check.
  128. cls: The class to check against.
  129. Returns:
  130. Whether the object is an instance of the class.
  131. """
  132. return isinstance(obj, get_base_class(cls))
  133. def rm(path: str):
  134. """Remove a file or directory.
  135. Args:
  136. path: The path to the file or directory.
  137. """
  138. if os.path.isdir(path):
  139. shutil.rmtree(path)
  140. elif os.path.isfile(path):
  141. os.remove(path)
  142. def cp(src: str, dest: str, overwrite: bool = True) -> bool:
  143. """Copy a file or directory.
  144. Args:
  145. src: The path to the file or directory.
  146. dest: The path to the destination.
  147. overwrite: Whether to overwrite the destination.
  148. Returns:
  149. Whether the copy was successful.
  150. """
  151. if src == dest:
  152. return False
  153. if not overwrite and os.path.exists(dest):
  154. return False
  155. if os.path.isdir(src):
  156. rm(dest)
  157. shutil.copytree(src, dest)
  158. else:
  159. shutil.copyfile(src, dest)
  160. return True
  161. def mv(src: str, dest: str, overwrite: bool = True) -> bool:
  162. """Move a file or directory.
  163. Args:
  164. src: The path to the file or directory.
  165. dest: The path to the destination.
  166. overwrite: Whether to overwrite the destination.
  167. Returns:
  168. Whether the move was successful.
  169. """
  170. if src == dest:
  171. return False
  172. if not overwrite and os.path.exists(dest):
  173. return False
  174. rm(dest)
  175. shutil.move(src, dest)
  176. return True
  177. def mkdir(path: str):
  178. """Create a directory.
  179. Args:
  180. path: The path to the directory.
  181. """
  182. if not os.path.exists(path):
  183. os.makedirs(path)
  184. def ln(src: str, dest: str, overwrite: bool = False) -> bool:
  185. """Create a symbolic link.
  186. Args:
  187. src: The path to the file or directory.
  188. dest: The path to the destination.
  189. overwrite: Whether to overwrite the destination.
  190. Returns:
  191. Whether the link was successful.
  192. """
  193. if src == dest:
  194. return False
  195. if not overwrite and (os.path.exists(dest) or os.path.islink(dest)):
  196. return False
  197. if os.path.isdir(src):
  198. rm(dest)
  199. os.symlink(src, dest, target_is_directory=True)
  200. else:
  201. os.symlink(src, dest)
  202. return True
  203. def kill(pid):
  204. """Kill a process.
  205. Args:
  206. pid: The process ID.
  207. """
  208. os.kill(pid, signal.SIGTERM)
  209. def which(program: str) -> Optional[str]:
  210. """Find the path to an executable.
  211. Args:
  212. program: The name of the executable.
  213. Returns:
  214. The path to the executable.
  215. """
  216. return shutil.which(program)
  217. def get_config() -> Config:
  218. """Get the app config.
  219. Returns:
  220. The app config.
  221. """
  222. from pynecone.config import Config
  223. sys.path.append(os.getcwd())
  224. try:
  225. return __import__(constants.CONFIG_MODULE).config
  226. except ImportError:
  227. return Config(app_name="")
  228. def check_node_version(min_version):
  229. """Check the version of Node.js.
  230. Args:
  231. min_version: The minimum version of Node.js required.
  232. Returns:
  233. Whether the version of Node.js is high enough.
  234. """
  235. try:
  236. # Run the node -v command and capture the output
  237. result = subprocess.run(
  238. ["node", "-v"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
  239. )
  240. # The output will be in the form "vX.Y.Z", so we can split it on the "v" character and take the second part
  241. version = result.stdout.decode().strip().split("v")[1]
  242. # Compare the version numbers
  243. return version.split(".") >= min_version.split(".")
  244. except Exception as e:
  245. return False
  246. def get_package_manager() -> str:
  247. """Get the package manager executable.
  248. Returns:
  249. The path to the package manager.
  250. Raises:
  251. FileNotFoundError: If bun or npm is not installed.
  252. Exit: If the app directory is invalid.
  253. """
  254. # Check that the node version is valid.
  255. if not check_node_version(constants.MIN_NODE_VERSION):
  256. console.print(
  257. f"[red]Node.js version {constants.MIN_NODE_VERSION} or higher is required to run Pynecone."
  258. )
  259. raise typer.Exit()
  260. # On Windows, we use npm instead of bun.
  261. if platform.system() == "Windows":
  262. npm_path = which("npm")
  263. if npm_path is None:
  264. raise FileNotFoundError("Pynecone requires npm to be installed on Windows.")
  265. return npm_path
  266. # On other platforms, we use bun.
  267. return os.path.expandvars(get_config().bun_path)
  268. def get_app() -> ModuleType:
  269. """Get the app module based on the default config.
  270. Returns:
  271. The app based on the default config.
  272. """
  273. config = get_config()
  274. module = ".".join([config.app_name, config.app_name])
  275. app = __import__(module, fromlist=(constants.APP_VAR,))
  276. return app
  277. def create_config(app_name: str):
  278. """Create a new pcconfig file.
  279. Args:
  280. app_name: The name of the app.
  281. """
  282. # Import here to avoid circular imports.
  283. from pynecone.compiler import templates
  284. with open(constants.CONFIG_FILE, "w") as f:
  285. f.write(templates.PCCONFIG.format(app_name=app_name))
  286. def initialize_app_directory(app_name: str):
  287. """Initialize the app directory on pc init.
  288. Args:
  289. app_name: The name of the app.
  290. """
  291. console.log("Initializing the app directory.")
  292. cp(constants.APP_TEMPLATE_DIR, app_name)
  293. mv(
  294. os.path.join(app_name, constants.APP_TEMPLATE_FILE),
  295. os.path.join(app_name, app_name + constants.PY_EXT),
  296. )
  297. cp(constants.ASSETS_TEMPLATE_DIR, constants.APP_ASSETS_DIR)
  298. def initialize_web_directory():
  299. """Initialize the web directory on pc init."""
  300. console.log("Initializing the web directory.")
  301. rm(os.path.join(constants.WEB_TEMPLATE_DIR, constants.NODE_MODULES))
  302. rm(os.path.join(constants.WEB_TEMPLATE_DIR, constants.PACKAGE_LOCK))
  303. cp(constants.WEB_TEMPLATE_DIR, constants.WEB_DIR)
  304. def install_bun():
  305. """Install bun onto the user's system."""
  306. # Bun is not supported on Windows.
  307. if platform.system() == "Windows":
  308. console.log("Skipping bun installation on Windows.")
  309. return
  310. # Only install if bun is not already installed.
  311. if not os.path.exists(get_package_manager()):
  312. console.log("Installing bun...")
  313. os.system(constants.INSTALL_BUN)
  314. def install_frontend_packages():
  315. """Install the frontend packages."""
  316. # Install the base packages.
  317. subprocess.run(
  318. [get_package_manager(), "install"], cwd=constants.WEB_DIR, stdout=PIPE
  319. )
  320. # Install the app packages.
  321. packages = get_config().frontend_packages
  322. if len(packages) > 0:
  323. subprocess.run(
  324. [get_package_manager(), "add", *packages],
  325. cwd=constants.WEB_DIR,
  326. stdout=PIPE,
  327. )
  328. def is_initialized() -> bool:
  329. """Check whether the app is initialized.
  330. Returns:
  331. Whether the app is initialized in the current directory.
  332. """
  333. return os.path.exists(constants.CONFIG_FILE) and os.path.exists(constants.WEB_DIR)
  334. def export_app(app: App, zip: bool = False):
  335. """Zip up the app for deployment.
  336. Args:
  337. app: The app.
  338. zip: Whether to zip the app.
  339. """
  340. # Force compile the app.
  341. app.compile(force_compile=True)
  342. # Remove the static folder.
  343. rm(constants.WEB_STATIC_DIR)
  344. # Export the Next app.
  345. subprocess.run([get_package_manager(), "run", "export"], cwd=constants.WEB_DIR)
  346. # Zip up the app.
  347. if zip:
  348. cmd = r"cd .web/_static && zip -r ../../frontend.zip ./* && cd ../.. && zip -r backend.zip ./* -x .web/\* ./assets\* ./frontend.zip\* ./backend.zip\*"
  349. os.system(cmd)
  350. def setup_frontend():
  351. """Set up the frontend."""
  352. # Initialize the web directory if it doesn't exist.
  353. cp(constants.WEB_TEMPLATE_DIR, constants.WEB_DIR, overwrite=False)
  354. # Install the frontend packages.
  355. console.rule("[bold]Installing frontend packages")
  356. install_frontend_packages()
  357. # Link the assets folder.
  358. ln(src=os.path.join("..", constants.APP_ASSETS_DIR), dest=constants.WEB_ASSETS_DIR)
  359. def run_frontend(app: App):
  360. """Run the frontend.
  361. Args:
  362. app: The app.
  363. """
  364. # Set up the frontend.
  365. setup_frontend()
  366. # Compile the frontend.
  367. app.compile(force_compile=True)
  368. # Run the frontend in development mode.
  369. console.rule("[bold green]App Running")
  370. subprocess.Popen([get_package_manager(), "run", "dev"], cwd=constants.WEB_DIR)
  371. def run_frontend_prod(app: App):
  372. """Run the frontend.
  373. Args:
  374. app: The app.
  375. """
  376. # Set up the frontend.
  377. setup_frontend()
  378. # Export the app.
  379. export_app(app)
  380. # Run the frontend in production mode.
  381. subprocess.Popen([get_package_manager(), "run", "prod"], cwd=constants.WEB_DIR)
  382. def get_num_workers() -> int:
  383. """Get the number of backend worker processes.
  384. Returns:
  385. The number of backend worker processes.
  386. """
  387. if get_redis() is None:
  388. # If there is no redis, then just use 1 worker.
  389. return 1
  390. # Use the number of cores * 2 + 1.
  391. return (os.cpu_count() or 1) * 2 + 1
  392. def run_backend(app_name: str):
  393. """Run the backend.
  394. Args:
  395. app_name: The app name.
  396. """
  397. command = constants.RUN_BACKEND + [
  398. f"{app_name}:{constants.APP_VAR}.{constants.API_VAR}"
  399. ]
  400. subprocess.run(command)
  401. def run_backend_prod(app_name: str):
  402. """Run the backend.
  403. Args:
  404. app_name: The app name.
  405. """
  406. num_workers = get_num_workers()
  407. command = constants.RUN_BACKEND_PROD + [
  408. "--workers",
  409. str(num_workers),
  410. "--threads",
  411. str(num_workers),
  412. f"{app_name}:{constants.APP_VAR}()",
  413. ]
  414. subprocess.run(command)
  415. def get_production_backend_url() -> str:
  416. """Get the production backend URL.
  417. Returns:
  418. The production backend URL.
  419. """
  420. config = get_config()
  421. return constants.PRODUCTION_BACKEND_URL.format(
  422. username=config.username,
  423. app_name=config.app_name,
  424. )
  425. def to_snake_case(text: str) -> str:
  426. """Convert a string to snake case.
  427. The words in the text are converted to lowercase and
  428. separated by underscores.
  429. Args:
  430. text: The string to convert.
  431. Returns:
  432. The snake case string.
  433. """
  434. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  435. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
  436. def to_camel_case(text: str) -> str:
  437. """Convert a string to camel case.
  438. The first word in the text is converted to lowercase and
  439. the rest of the words are converted to title case, removing underscores.
  440. Args:
  441. text: The string to convert.
  442. Returns:
  443. The camel case string.
  444. """
  445. if "_" not in text:
  446. return text
  447. camel = "".join(
  448. word.capitalize() if i > 0 else word.lower()
  449. for i, word in enumerate(text.lstrip("_").split("_"))
  450. )
  451. prefix = "_" if text.startswith("_") else ""
  452. return prefix + camel
  453. def to_title(text: str) -> str:
  454. """Convert a string from snake case to a title.
  455. Each word is converted to title case and separated by a space.
  456. Args:
  457. text: The string to convert.
  458. Returns:
  459. The title case string.
  460. """
  461. return " ".join(word.capitalize() for word in text.split("_"))
  462. WRAP_MAP = {
  463. "{": "}",
  464. "(": ")",
  465. "[": "]",
  466. "<": ">",
  467. '"': '"',
  468. "'": "'",
  469. "`": "`",
  470. }
  471. def get_close_char(open: str, close: Optional[str] = None) -> str:
  472. """Check if the given character is a valid brace.
  473. Args:
  474. open: The open character.
  475. close: The close character if provided.
  476. Returns:
  477. The close character.
  478. Raises:
  479. ValueError: If the open character is not a valid brace.
  480. """
  481. if close is not None:
  482. return close
  483. if open not in WRAP_MAP:
  484. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  485. return WRAP_MAP[open]
  486. def is_wrapped(text: str, open: str, close: Optional[str] = None) -> bool:
  487. """Check if the given text is wrapped in the given open and close characters.
  488. Args:
  489. text: The text to check.
  490. open: The open character.
  491. close: The close character.
  492. Returns:
  493. Whether the text is wrapped.
  494. """
  495. close = get_close_char(open, close)
  496. return text.startswith(open) and text.endswith(close)
  497. def wrap(
  498. text: str,
  499. open: str,
  500. close: Optional[str] = None,
  501. check_first: bool = True,
  502. num: int = 1,
  503. ) -> str:
  504. """Wrap the given text in the given open and close characters.
  505. Args:
  506. text: The text to wrap.
  507. open: The open character.
  508. close: The close character.
  509. check_first: Whether to check if the text is already wrapped.
  510. num: The number of times to wrap the text.
  511. Returns:
  512. The wrapped text.
  513. """
  514. close = get_close_char(open, close)
  515. # If desired, check if the text is already wrapped in braces.
  516. if check_first and is_wrapped(text=text, open=open, close=close):
  517. return text
  518. # Wrap the text in braces.
  519. return f"{open * num}{text}{close * num}"
  520. def indent(text: str, indent_level: int = 2) -> str:
  521. """Indent the given text by the given indent level.
  522. Args:
  523. text: The text to indent.
  524. indent_level: The indent level.
  525. Returns:
  526. The indented text.
  527. """
  528. lines = text.splitlines()
  529. if len(lines) < 2:
  530. return text
  531. return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep
  532. def get_page_path(path: str) -> str:
  533. """Get the path of the compiled JS file for the given page.
  534. Args:
  535. path: The path of the page.
  536. Returns:
  537. The path of the compiled JS file.
  538. """
  539. return os.path.join(constants.WEB_PAGES_DIR, path + constants.JS_EXT)
  540. def get_theme_path() -> str:
  541. """Get the path of the base theme style.
  542. Returns:
  543. The path of the theme style.
  544. """
  545. return os.path.join(constants.WEB_UTILS_DIR, constants.THEME + constants.JS_EXT)
  546. def get_path_args(path: str) -> List[str]:
  547. """Get the path arguments for the given path.
  548. Args:
  549. path: The path to get the arguments for.
  550. Returns:
  551. The path arguments.
  552. """
  553. # Import here to avoid circular imports.
  554. from pynecone.var import BaseVar
  555. # Regex to check for path args.
  556. check = re.compile(r"^\[(.+)\]$")
  557. # Iterate over the path parts and check for path args.
  558. args = []
  559. for part in os.path.split(path):
  560. match = check.match(part)
  561. if match:
  562. # Add the path arg to the list.
  563. v = BaseVar(
  564. name=match.groups()[0],
  565. type_=str,
  566. state=f"{constants.ROUTER}.query",
  567. )
  568. args.append(v)
  569. return args
  570. def write_page(path: str, code: str):
  571. """Write the given code to the given path.
  572. Args:
  573. path: The path to write the code to.
  574. code: The code to write.
  575. """
  576. mkdir(os.path.dirname(path))
  577. with open(path, "w") as f:
  578. f.write(code)
  579. def format_route(route: str):
  580. """Format the given route.
  581. Args:
  582. route: The route to format.
  583. Returns:
  584. The formatted route.
  585. """
  586. route = route.strip(os.path.sep)
  587. route = to_snake_case(route).replace("_", "-")
  588. if route == "":
  589. return constants.INDEX_ROUTE
  590. return route
  591. def format_cond(
  592. cond: str, true_value: str, false_value: str = '""', is_nested: bool = False
  593. ) -> str:
  594. """Format a conditional expression.
  595. Args:
  596. cond: The cond.
  597. true_value: The value to return if the cond is true.
  598. false_value: The value to return if the cond is false.
  599. is_nested: Whether the cond is nested.
  600. Returns:
  601. The formatted conditional expression.
  602. """
  603. expr = f"{cond} ? {true_value} : {false_value}"
  604. if not is_nested:
  605. expr = wrap(expr, "{")
  606. return expr
  607. def format_event_fn(fn: Callable) -> str:
  608. """Format a function as an event.
  609. Args:
  610. fn: The function to format.
  611. Returns:
  612. The formatted function.
  613. """
  614. from pynecone.event import EventHandler
  615. if isinstance(fn, EventHandler):
  616. fn = fn.fn
  617. return to_snake_case(fn.__qualname__)
  618. def format_event(event_spec: EventSpec) -> str:
  619. """Format an event.
  620. Args:
  621. event_spec: The event to format.
  622. Returns:
  623. The compiled event.
  624. """
  625. args = ",".join([":".join((name, val)) for name, val in event_spec.args])
  626. return f"E(\"{format_event_fn(event_spec.handler.fn)}\", {wrap(args, '{')})"
  627. USED_VARIABLES = set()
  628. def get_unique_variable_name() -> str:
  629. """Get a unique variable name.
  630. Returns:
  631. The unique variable name.
  632. """
  633. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  634. if name not in USED_VARIABLES:
  635. USED_VARIABLES.add(name)
  636. return name
  637. return get_unique_variable_name()
  638. def get_default_app_name() -> str:
  639. """Get the default app name.
  640. The default app name is the name of the current directory.
  641. Returns:
  642. The default app name.
  643. """
  644. return os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  645. def is_dataframe(value: Type) -> bool:
  646. """Check if the given value is a dataframe.
  647. Args:
  648. value: The value to check.
  649. Returns:
  650. Whether the value is a dataframe.
  651. """
  652. return value.__name__ == "DataFrame"
  653. def format_state(value: Any) -> Dict:
  654. """Recursively format values in the given state.
  655. Args:
  656. value: The state to format.
  657. Returns:
  658. The formatted state.
  659. Raises:
  660. TypeError: If the given value is not a valid state.
  661. """
  662. # Handle dicts.
  663. if isinstance(value, dict):
  664. return {k: format_state(v) for k, v in value.items()}
  665. # Return state vars as is.
  666. if isinstance(value, StateBases):
  667. return value
  668. # Convert plotly figures to JSON.
  669. if isinstance(value, go.Figure):
  670. return json.loads(to_json(value))["data"]
  671. # Convert pandas dataframes to JSON.
  672. if is_dataframe(type(value)):
  673. return {
  674. "columns": value.columns.tolist(),
  675. "data": value.values.tolist(),
  676. }
  677. raise TypeError(
  678. "State vars must be primitive Python types, "
  679. "or subclasses of pc.Base. "
  680. f"Got var of type {type(value)}."
  681. )
  682. def get_event(state, event):
  683. """Get the event from the given state.
  684. Args:
  685. state: The state.
  686. event: The event.
  687. Returns:
  688. The event.
  689. """
  690. return f"{state.get_name()}.{event}"
  691. def format_string(string: str) -> str:
  692. """Format the given string as a JS string literal..
  693. Args:
  694. string: The string to format.
  695. Returns:
  696. The formatted string.
  697. """
  698. # Escape backticks.
  699. string = string.replace(r"\`", "`")
  700. string = string.replace("`", r"\`")
  701. # Wrap the string so it looks like {`string`}.
  702. string = wrap(string, "`")
  703. string = wrap(string, "{")
  704. return string
  705. def call_event_handler(event_handler: EventHandler, arg: Var) -> EventSpec:
  706. """Call an event handler to get the event spec.
  707. This function will inspect the function signature of the event handler.
  708. If it takes in an arg, the arg will be passed to the event handler.
  709. Otherwise, the event handler will be called with no args.
  710. Args:
  711. event_handler: The event handler.
  712. arg: The argument to pass to the event handler.
  713. Returns:
  714. The event spec from calling the event handler.
  715. """
  716. args = inspect.getfullargspec(event_handler.fn).args
  717. if len(args) == 1:
  718. return event_handler()
  719. assert (
  720. len(args) == 2
  721. ), f"Event handler {event_handler.fn} must have 1 or 2 arguments."
  722. return event_handler(arg)
  723. def call_event_fn(fn: Callable, arg: Var) -> List[EventSpec]:
  724. """Call a function to a list of event specs.
  725. The function should return either a single EventSpec or a list of EventSpecs.
  726. If the function takes in an arg, the arg will be passed to the function.
  727. Otherwise, the function will be called with no args.
  728. Args:
  729. fn: The function to call.
  730. arg: The argument to pass to the function.
  731. Returns:
  732. The event specs from calling the function.
  733. Raises:
  734. ValueError: If the lambda has an invalid signature.
  735. """
  736. args = inspect.getfullargspec(fn).args
  737. if len(args) == 0:
  738. out = fn()
  739. elif len(args) == 1:
  740. out = fn(arg)
  741. else:
  742. raise ValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  743. if not isinstance(out, List):
  744. out = [out]
  745. return out
  746. def get_handler_args(event_spec: EventSpec, arg: Var) -> Tuple[Tuple[str, str], ...]:
  747. """Get the handler args for the given event spec.
  748. Args:
  749. event_spec: The event spec.
  750. arg: The controlled event argument.
  751. Returns:
  752. The handler args.
  753. """
  754. args = inspect.getfullargspec(event_spec.handler.fn).args
  755. if len(args) > 2:
  756. return event_spec.args
  757. else:
  758. return ((args[1], arg.name),)
  759. def fix_events(events: Optional[List[Event]], token: str) -> List[Event]:
  760. """Fix a list of events returned by an event handler.
  761. Args:
  762. events: The events to fix.
  763. token: The user token.
  764. Returns:
  765. The fixed events.
  766. """
  767. from pynecone.event import Event, EventHandler, EventSpec
  768. # If the event handler returns nothing, return an empty list.
  769. if events is None:
  770. return []
  771. # If the handler returns a single event, wrap it in a list.
  772. if not isinstance(events, List):
  773. events = [events]
  774. # Fix the events created by the handler.
  775. out = []
  776. for e in events:
  777. # If it is already an event, don't modify it.
  778. if isinstance(e, Event):
  779. name = e.name
  780. payload = e.payload
  781. # Otherwise, create an event from the event spec.
  782. else:
  783. if isinstance(e, EventHandler):
  784. e = e()
  785. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  786. name = format_event_fn(e.handler.fn)
  787. payload = dict(e.args)
  788. # Create an event and append it to the list.
  789. out.append(
  790. Event(
  791. token=token,
  792. name=name,
  793. payload=payload,
  794. )
  795. )
  796. return out
  797. def merge_imports(*imports) -> ImportDict:
  798. """Merge two import dicts together.
  799. Args:
  800. *imports: The list of import dicts to merge.
  801. Returns:
  802. The merged import dicts.
  803. """
  804. all_imports = defaultdict(set)
  805. for import_dict in imports:
  806. for lib, fields in import_dict.items():
  807. for field in fields:
  808. all_imports[lib].add(field)
  809. return all_imports
  810. def get_hydrate_event(state) -> str:
  811. """Get the name of the hydrate event for the state.
  812. Args:
  813. state: The state.
  814. Returns:
  815. The name of the hydrate event.
  816. """
  817. return get_event(state, constants.HYDRATE)
  818. def get_redis() -> Optional[Redis]:
  819. """Get the redis client.
  820. Returns:
  821. The redis client.
  822. """
  823. config = get_config()
  824. if config.redis_url is None:
  825. return None
  826. redis_url, redis_port = config.redis_url.split(":")
  827. print("Using redis at", config.redis_url)
  828. return Redis(host=redis_url, port=int(redis_port), db=0)
  829. # Store this here for performance.
  830. StateBases = get_base_class(StateVar)