utils.py 32 KB

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