utils.py 27 KB

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