constants.py 8.9 KB

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