utils.py 30 KB

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