constants.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. """Constants used throughout the package."""
  2. import os
  3. import re
  4. from enum import Enum
  5. from types import SimpleNamespace
  6. from typing import Any, Type
  7. # importlib is only available for Python 3.8+ so we need the backport for Python 3.7
  8. try:
  9. from importlib import metadata
  10. except ImportError:
  11. import importlib_metadata as metadata # pyright: ignore[reportMissingImports]
  12. def get_value(key: str, default: Any = None, type_: Type = str) -> Type:
  13. """Get the value for the constant.
  14. Obtain os env value and cast non-string types into
  15. their original types.
  16. Args:
  17. key: constant name.
  18. default: default value if key doesn't exist.
  19. type_: the type of the constant.
  20. Returns:
  21. the value of the constant in its designated type
  22. """
  23. value = os.getenv(key, default)
  24. try:
  25. if value and type_ != str:
  26. value = eval(value)
  27. except Exception:
  28. pass
  29. finally:
  30. # Special case for db_url expects None to be a valid input when
  31. # user explicitly overrides db_url as None
  32. return value if value != "None" else None # noqa B012
  33. # App names and versions.
  34. # The name of the Reflex package.
  35. MODULE_NAME = "reflex"
  36. # The current version of Reflex.
  37. VERSION = metadata.version(MODULE_NAME)
  38. # Minimum version of Node.js required to run Reflex.
  39. MIN_NODE_VERSION = "16.8.0"
  40. # Valid bun versions.
  41. MIN_BUN_VERSION = "0.5.9"
  42. MAX_BUN_VERSION = "0.6.9"
  43. # Files and directories used to init a new project.
  44. # The root directory of the reflex library.
  45. ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  46. # The name of the assets directory.
  47. APP_ASSETS_DIR = "assets"
  48. # The template directory used during reflex init.
  49. TEMPLATE_DIR = os.path.join(ROOT_DIR, MODULE_NAME, ".templates")
  50. # The web subdirectory of the template directory.
  51. WEB_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, "web")
  52. # The assets subdirectory of the template directory.
  53. ASSETS_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, APP_ASSETS_DIR)
  54. # The jinja template directory.
  55. JINJA_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, "jinja")
  56. # The frontend directories in a project.
  57. # The web folder where the NextJS app is compiled to.
  58. WEB_DIR = ".web"
  59. # The name of the utils file.
  60. UTILS_DIR = "utils"
  61. # The name of the state file.
  62. STATE_PATH = "/".join([UTILS_DIR, "state"])
  63. # The name of the components file.
  64. COMPONENTS_PATH = "/".join([UTILS_DIR, "components"])
  65. # The directory where the app pages are compiled to.
  66. WEB_PAGES_DIR = os.path.join(WEB_DIR, "pages")
  67. # The directory where the static build is located.
  68. WEB_STATIC_DIR = os.path.join(WEB_DIR, "_static")
  69. # The directory where the utils file is located.
  70. WEB_UTILS_DIR = os.path.join(WEB_DIR, UTILS_DIR)
  71. # The directory where the assets are located.
  72. WEB_ASSETS_DIR = os.path.join(WEB_DIR, "public")
  73. # The Tailwind config.
  74. TAILWIND_CONFIG = os.path.join(WEB_DIR, "tailwind.config.js")
  75. # Default Tailwind content paths
  76. TAILWIND_CONTENT = ["./pages/**/*.{js,ts,jsx,tsx}"]
  77. # The NextJS config file
  78. NEXT_CONFIG_FILE = "next.config.js"
  79. # The sitemap config file.
  80. SITEMAP_CONFIG_FILE = os.path.join(WEB_DIR, "next-sitemap.config.js")
  81. # The node modules directory.
  82. NODE_MODULES = "node_modules"
  83. # The package lock file.
  84. PACKAGE_LOCK = "package-lock.json"
  85. # The reflex json file.
  86. REFLEX_JSON = os.path.join(WEB_DIR, "reflex.json")
  87. # The env json file.
  88. ENV_JSON = os.path.join(WEB_DIR, "env.json")
  89. # Commands to run the app.
  90. DOT_ENV_FILE = ".env"
  91. # The frontend default port.
  92. FRONTEND_PORT = get_value("FRONTEND_PORT", "3000")
  93. # The backend default port.
  94. BACKEND_PORT = get_value("BACKEND_PORT", "8000")
  95. # The backend api url.
  96. API_URL = get_value("API_URL", "http://localhost:8000")
  97. # The deploy url
  98. DEPLOY_URL = get_value("DEPLOY_URL")
  99. # bun root location
  100. BUN_ROOT_PATH = "$HOME/.bun"
  101. # The default path where bun is installed.
  102. BUN_PATH = get_value("BUN_PATH", f"{BUN_ROOT_PATH}/bin/bun")
  103. # Command to install bun.
  104. INSTALL_BUN = f"curl -fsSL https://bun.sh/install | bash -s -- bun-v{MAX_BUN_VERSION}"
  105. # Default host in dev mode.
  106. BACKEND_HOST = get_value("BACKEND_HOST", "0.0.0.0")
  107. # The default timeout when launching the gunicorn server.
  108. TIMEOUT = get_value("TIMEOUT", 120, type_=int)
  109. # The command to run the backend in production mode.
  110. RUN_BACKEND_PROD = f"gunicorn --worker-class uvicorn.workers.UvicornH11Worker --preload --timeout {TIMEOUT} --log-level critical".split()
  111. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {TIMEOUT}".split()
  112. # Socket.IO web server
  113. PING_INTERVAL = 25
  114. PING_TIMEOUT = 120
  115. # flag to make the engine print all the SQL statements it executes
  116. SQLALCHEMY_ECHO = get_value("SQLALCHEMY_ECHO", False, type_=bool)
  117. # Compiler variables.
  118. # The extension for compiled Javascript files.
  119. JS_EXT = ".js"
  120. # The extension for python files.
  121. PY_EXT = ".py"
  122. # The expected variable name where the rx.App is stored.
  123. APP_VAR = "app"
  124. # The expected variable name where the API object is stored for deployment.
  125. API_VAR = "api"
  126. # The name of the router variable.
  127. ROUTER = "router"
  128. # The name of the socket variable.
  129. SOCKET = "socket"
  130. # The name of the variable to hold API results.
  131. RESULT = "result"
  132. # The name of the final variable.
  133. FINAL = "final"
  134. # The name of the process variable.
  135. PROCESSING = "processing"
  136. # The name of the state variable.
  137. STATE = "state"
  138. # The name of the events variable.
  139. EVENTS = "events"
  140. # The name of the initial hydrate event.
  141. HYDRATE = "hydrate"
  142. # The name of the is_hydrated variable.
  143. IS_HYDRATED = "is_hydrated"
  144. # The name of the index page.
  145. INDEX_ROUTE = "index"
  146. # The name of the document root page.
  147. DOCUMENT_ROOT = "_document"
  148. # The name of the theme page.
  149. THEME = "theme"
  150. # The prefix used to create setters for state vars.
  151. SETTER_PREFIX = "set_"
  152. # The name of the frontend zip during deployment.
  153. FRONTEND_ZIP = "frontend.zip"
  154. # The name of the backend zip during deployment.
  155. BACKEND_ZIP = "backend.zip"
  156. # The name of the sqlite database.
  157. DB_NAME = os.getenv("DB_NAME", "reflex.db")
  158. # The sqlite url.
  159. DB_URL = get_value("DB_URL", f"sqlite:///{DB_NAME}")
  160. # The redis url
  161. REDIS_URL = get_value("REDIS_URL")
  162. # The default title to show for Reflex apps.
  163. DEFAULT_TITLE = "Reflex App"
  164. # The default description to show for Reflex apps.
  165. DEFAULT_DESCRIPTION = "A Reflex app."
  166. # The default image to show for Reflex apps.
  167. DEFAULT_IMAGE = "favicon.ico"
  168. # The default meta list to show for Reflex apps.
  169. DEFAULT_META_LIST = []
  170. # The gitignore file.
  171. GITIGNORE_FILE = ".gitignore"
  172. # Files to gitignore.
  173. DEFAULT_GITIGNORE = {WEB_DIR, DB_NAME, "__pycache__/", "*.py[cod]"}
  174. # The name of the reflex config module.
  175. CONFIG_MODULE = "rxconfig"
  176. # The python config file.
  177. CONFIG_FILE = f"{CONFIG_MODULE}{PY_EXT}"
  178. # The previous config file.
  179. OLD_CONFIG_FILE = f"pcconfig{PY_EXT}"
  180. # The deployment URL.
  181. PRODUCTION_BACKEND_URL = "https://{username}-{app_name}.api.pynecone.app"
  182. # Token expiration time in seconds.
  183. TOKEN_EXPIRATION = 60 * 60
  184. # Env modes
  185. class Env(str, Enum):
  186. """The environment modes."""
  187. DEV = "dev"
  188. PROD = "prod"
  189. # Log levels
  190. class LogLevel(str, Enum):
  191. """The log levels."""
  192. DEBUG = "debug"
  193. INFO = "info"
  194. WARNING = "warning"
  195. ERROR = "error"
  196. CRITICAL = "critical"
  197. # Templates
  198. class Template(str, Enum):
  199. """The templates to use for the app."""
  200. DEFAULT = "default"
  201. COUNTER = "counter"
  202. class Endpoint(Enum):
  203. """Endpoints for the reflex backend API."""
  204. PING = "ping"
  205. EVENT = "event"
  206. UPLOAD = "upload"
  207. def __str__(self) -> str:
  208. """Get the string representation of the endpoint.
  209. Returns:
  210. The path for the endpoint.
  211. """
  212. return f"/{self.value}"
  213. def get_url(self) -> str:
  214. """Get the URL for the endpoint.
  215. Returns:
  216. The full URL for the endpoint.
  217. """
  218. # Import here to avoid circular imports.
  219. from reflex.config import get_config
  220. # Get the API URL from the config.
  221. config = get_config()
  222. url = "".join([config.api_url, str(self)])
  223. # The event endpoint is a websocket.
  224. if self == Endpoint.EVENT:
  225. # Replace the protocol with ws.
  226. url = url.replace("https://", "wss://").replace("http://", "ws://")
  227. # Return the url.
  228. return url
  229. class SocketEvent(Enum):
  230. """Socket events sent by the reflex backend API."""
  231. PING = "ping"
  232. EVENT = "event"
  233. def __str__(self) -> str:
  234. """Get the string representation of the event name.
  235. Returns:
  236. The event name string.
  237. """
  238. return str(self.value)
  239. class Transports(Enum):
  240. """Socket transports used by the reflex backend API."""
  241. POLLING_WEBSOCKET = "['polling', 'websocket']"
  242. WEBSOCKET_POLLING = "['websocket', 'polling']"
  243. WEBSOCKET_ONLY = "['websocket']"
  244. POLLING_ONLY = "['polling']"
  245. def __str__(self) -> str:
  246. """Get the string representation of the transports.
  247. Returns:
  248. The transports string.
  249. """
  250. return str(self.value)
  251. def get_transports(self) -> str:
  252. """Get the transports config for the backend.
  253. Returns:
  254. The transports config for the backend.
  255. """
  256. # Import here to avoid circular imports.
  257. from reflex.config import get_config
  258. # Get the API URL from the config.
  259. config = get_config()
  260. return str(config.backend_transports)
  261. class RouteArgType(SimpleNamespace):
  262. """Type of dynamic route arg extracted from URI route."""
  263. # Typecast to str is needed for Enum to work.
  264. SINGLE = str("arg_single")
  265. LIST = str("arg_list")
  266. # the name of the backend var containing path and client information
  267. ROUTER_DATA = "router_data"
  268. class RouteVar(SimpleNamespace):
  269. """Names of variables used in the router_data dict stored in State."""
  270. CLIENT_IP = "ip"
  271. CLIENT_TOKEN = "token"
  272. HEADERS = "headers"
  273. PATH = "pathname"
  274. SESSION_ID = "sid"
  275. QUERY = "query"
  276. COOKIE = "cookie"
  277. class RouteRegex(SimpleNamespace):
  278. """Regex used for extracting route args in route."""
  279. ARG = re.compile(r"\[(?!\.)([^\[\]]+)\]")
  280. # group return the catchall pattern (i.e. "[[..slug]]")
  281. CATCHALL = re.compile(r"(\[?\[\.{3}(?![0-9]).*\]?\])")
  282. # group return the arg name (i.e. "slug")
  283. STRICT_CATCHALL = re.compile(r"\[\.{3}([a-zA-Z_][\w]*)\]")
  284. # group return the arg name (i.e. "slug")
  285. OPT_CATCHALL = re.compile(r"\[\[\.{3}([a-zA-Z_][\w]*)\]\]")
  286. # 404 variables
  287. ROOT_404 = ""
  288. SLUG_404 = "[..._]"
  289. TITLE_404 = "404 - Not Found"
  290. FAVICON_404 = "favicon.ico"
  291. DESCRIPTION_404 = "The page was not found"
  292. # Color mode variables
  293. USE_COLOR_MODE = "useColorMode"
  294. COLOR_MODE = "colorMode"
  295. TOGGLE_COLOR_MODE = "toggleColorMode"
  296. # Server socket configuration variables
  297. CORS_ALLOWED_ORIGINS = get_value("CORS_ALLOWED_ORIGINS", ["*"], list)
  298. POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000
  299. # Alembic migrations
  300. ALEMBIC_CONFIG = os.environ.get("ALEMBIC_CONFIG", "alembic.ini")