utils.py 22 KB

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