Web apps in pure Python with reactive components and automatic frontend generation.
—
Core application management, reactive state system, page routing, and configuration for building full-stack web applications with automatic frontend generation and state synchronization.
The main App class provides the foundation for Reflex applications, handling page registration, routing, compilation, and server management.
@dataclasses.dataclass()
class App(MiddlewareMixin, LifespanMixin):
"""
Main application class for creating Reflex apps.
Handles page registration, routing, state management, and compilation
to React components with automatic backend integration.
App is a dataclass that contains configuration for the entire application.
"""
# The global theme for the entire app
theme: Component | None = dataclasses.field(
default_factory=lambda: themes.theme(accent_color="blue")
)
# The global style for the app
style: ComponentStyle = dataclasses.field(default_factory=dict)
# A list of URLs to stylesheets to include in the app
stylesheets: list[str] = dataclasses.field(default_factory=list)
# Whether to include CSS reset for margin and padding
reset_style: bool = dataclasses.field(default=True)
# A component that is present on every page
overlay_component: Component | ComponentCallable | None = dataclasses.field(
default=None
)
# Components to add to the head of every page
head_components: list[Component] = dataclasses.field(default_factory=list)
# The language to add to the html root tag of every page
html_lang: str | None = None
# Attributes to add to the html root tag of every page
html_custom_attrs: dict[str, str] | None = None
# Whether to enable state for the app
enable_state: bool = True
# Admin dashboard to view and manage the database
admin_dash: AdminDash | None = None
def add_page(
self,
component: Component | ComponentCallable,
route: str | None = None,
title: str | Var | None = None,
description: str | Var | None = None,
image: str | None = None,
meta: Sequence[Mapping[str, str]] | None = None,
on_load: EventType[()] | None = None
) -> None:
"""
Add a page to the application with routing and metadata.
Args:
component: Component function or instance to render
route: URL route path (defaults to function name)
title: Page title for SEO and browser tabs (can be Var for dynamic titles)
description: Page description for SEO meta tags (can be Var for dynamic descriptions)
image: Page image URL for social media sharing
meta: Additional HTML meta tags as sequence of mappings
on_load: Event handler(s) to execute when page loads
"""
...
def compile(self, force_compile: bool = False) -> None:
"""
Compile the application to React components.
Args:
force_compile: Whether to force recompilation even if no changes detected
"""
...
def __call__(self) -> ASGIApp:
"""
Get the ASGI app instance.
Returns:
The ASGI app for serving the application
"""
...The State system provides reactive state management with automatic frontend synchronization, computed variables, and type-safe state updates.
class BaseState(EvenMoreBasicBaseState):
"""
The core state class that all Reflex states inherit from.
Provides reactive state management with automatic frontend synchronization,
event handling, and state hierarchy management.
All user state classes should inherit from this class either directly
or through the State alias.
"""
# Class-level variable tracking
vars: ClassVar[dict[str, Var]] = {}
base_vars: ClassVar[dict[str, Var]] = {}
computed_vars: ClassVar[dict[str, ComputedVar]] = {}
inherited_vars: ClassVar[dict[str, Var]] = {}
backend_vars: ClassVar[dict[str, Var]] = {}
@classmethod
def get_parent_state(cls) -> type[BaseState] | None:
"""
Get the parent state class.
Returns:
The parent state class or None if this is a root state
Raises:
ValueError: If more than one parent state is found
"""
...
@classmethod
def get_root_state(cls) -> type[BaseState]:
"""
Get the root state class in the state hierarchy.
Returns:
The root state class
"""
...
@classmethod
def get_substates(cls) -> set[type[BaseState]]:
"""
Get all substate classes that inherit from this state.
Returns:
Set of substate classes
"""
...
@classmethod
def get_class_substate(cls, path: Sequence[str] | str) -> type[BaseState]:
"""
Get a substate class by path.
Args:
path: The path to the substate (dot-separated string or sequence)
Returns:
The substate class
"""
...
def get_substate(self, path: Sequence[str]) -> BaseState:
"""
Get a substate instance by path.
Args:
path: The path to the substate
Returns:
The substate instance
"""
...
async def get_state(self, state_cls: type[T_STATE]) -> T_STATE:
"""
Get an instance of another state class associated with this token.
Args:
state_cls: The state class to get an instance of
Returns:
Instance of the requested state class
"""
...
async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE:
"""
Get the value of a Var from another state.
Args:
var: The var to get the value for
Returns:
The current value of the var
"""
...
def get_delta(self) -> Delta:
"""
Get the state changes (delta) since last sync.
Returns:
Dictionary of changed state variables
"""
...
def get_value(self, key: str) -> Any:
"""
Get the value of a state field without proxying.
Args:
key: The field name
Returns:
The field value
"""
...
class State(BaseState):
"""
The app base state class - alias for BaseState.
This is the main state class that user applications should inherit from.
Includes hydration state tracking for client-server synchronization.
"""
# Whether the state has been hydrated on the frontend
is_hydrated: bool = False
@event
def set_is_hydrated(self, value: bool) -> None:
"""
Set the hydrated state.
Args:
value: The hydrated state
"""
...
class ComponentState(State, mixin=True):
"""
Base class for component-level state management.
Allows creation of a state instance per component, enabling
bundling of UI and state logic into a single class where each
instance has separate state.
Subclass this and define a get_component method that returns
the UI for the component instance.
"""
@classmethod
def get_component(cls, *children, **props) -> Component:
"""
Get the component instance for this state.
Args:
children: The children of the component
props: The props of the component
Returns:
The component instance
"""
...Reactive computed properties that automatically update when dependent state changes, with caching and dependency tracking.
@computed_var
def computed_property(self) -> ReturnType:
"""
Decorator for creating computed state variables.
Computed variables automatically recalculate when their dependencies
change and are cached until dependencies update.
Returns:
Computed value based on current state
"""
...
def var(func: Callable) -> ComputedVar:
"""
Alias for computed_var decorator.
Args:
func: Function to convert to computed variable
Returns:
ComputedVar instance with automatic dependency tracking
"""
...
def dynamic(func: Callable) -> DynamicRouteVar:
"""
Create dynamic route argument handler.
Args:
func: Function that processes dynamic route arguments
Returns:
DynamicRouteVar for handling URL parameters
"""
...Declarative page routing with metadata support, SEO optimization, and automatic route generation from component functions.
def page(
route: str | None = None,
title: str | None = None,
image: str | None = None,
description: str | None = None,
meta: list[dict] | None = None,
script_tags: list[dict] | None = None,
on_load: EventType | None = None
) -> Callable:
"""
Decorator for registering component functions as pages.
Automatically registers decorated functions with the app when
App.compile() is called, enabling clean route definition.
Args:
route: URL route path (defaults to function name)
title: Page title for browser tabs and SEO
image: Favicon or social media image URL
description: Meta description for SEO
meta: Additional HTML meta tags
script_tags: Custom script tags for the page
on_load: Event handlers to execute on page load
Returns:
Decorated function with page registration metadata
"""
...Usage example:
@rx.page(route="/dashboard", title="User Dashboard", on_load=State.load_user_data)
def dashboard():
return rx.vstack(
rx.heading("Dashboard"),
rx.text(f"Welcome, {State.username}"),
)Comprehensive configuration management for database connections, styling, deployment settings, and development options.
class Config:
"""
Application configuration management.
Centralizes settings for database, styling, deployment, and
development options with environment variable support.
"""
app_name: str
"""Application name used for compilation and deployment."""
db_url: str | None = None
"""Database connection URL (PostgreSQL, SQLite, etc.)."""
redis_url: str | None = None
"""Redis URL for session storage and caching."""
frontend_port: int = 3000
"""Port for the frontend development server."""
backend_port: int = 8000
"""Port for the backend API server."""
deploy_url: str | None = None
"""Base URL for production deployment."""
env: str = "dev"
"""Environment setting: 'dev', 'prod', or custom."""
tailwind: dict | None = None
"""Tailwind CSS configuration overrides."""
def __init__(self, **kwargs) -> None:
"""
Initialize configuration with optional overrides.
Args:
**kwargs: Configuration values to override defaults
"""
...
class DBConfig:
"""
Database configuration with PostgreSQL optimization.
Provides database connection management, migration settings,
and engine configuration for SQLAlchemy integration.
"""
db_url: str
"""Database connection URL."""
engine: Engine | None = None
"""SQLAlchemy engine instance (auto-created if None)."""
migrate: bool = True
"""Whether to run database migrations on startup."""
pool_size: int = 10
"""Connection pool size for database connections."""
max_overflow: int = 20
"""Maximum overflow connections beyond pool_size."""
def __init__(self, db_url: str, **kwargs) -> None:
"""
Initialize database configuration.
Args:
db_url: Database connection URL
**kwargs: Additional configuration options
"""
...Built-in file upload handling with validation, storage management, and progress tracking for web applications.
class UploadFile:
"""
File upload handling with validation and storage.
Represents an uploaded file with metadata, validation,
and storage utilities for processing user uploads.
"""
filename: str
"""Original filename from the client."""
content_type: str
"""MIME type of the uploaded file."""
size: int
"""File size in bytes."""
file: BinaryIO
"""File-like object for reading file contents."""
def read(self) -> bytes:
"""
Read the complete file contents.
Returns:
Complete file contents as bytes
"""
...
def save(self, path: str) -> None:
"""
Save the file to a specified path.
Args:
path: File system path to save the file
"""
...from typing import Any, Callable, Dict, List, Optional, Union
from datetime import datetime
from sqlalchemy import Engine
# Core Application Types
Component = Any # Reflex component instance
EventType = Callable | EventHandler | list[EventHandler] # Event handler types
# State Types
Delta = Dict[str, Any] # State change dictionary
StateUpdate = Dict[str, Any] # State update payload
# Configuration Types
class RouterData:
"""Router data with current page information."""
path: str
query: Dict[str, str]
headers: Dict[str, str]
session_id: str
# Variable Types
ComputedVar = Any # Computed reactive variable
DynamicRouteVar = Any # Dynamic route parameter variable
# File Types
from typing import BinaryIO
FileUpload = BinaryIO | UploadFileInstall with Tessl CLI
npx tessl i tessl/pypi-reflex