0
# Core Framework
1
2
Core application management, reactive state system, page routing, and configuration for building full-stack web applications with automatic frontend generation and state synchronization.
3
4
## Capabilities
5
6
### Application Management
7
8
The main App class provides the foundation for Reflex applications, handling page registration, routing, compilation, and server management.
9
10
```python { .api }
11
@dataclasses.dataclass()
12
class App(MiddlewareMixin, LifespanMixin):
13
"""
14
Main application class for creating Reflex apps.
15
16
Handles page registration, routing, state management, and compilation
17
to React components with automatic backend integration.
18
19
App is a dataclass that contains configuration for the entire application.
20
"""
21
22
# The global theme for the entire app
23
theme: Component | None = dataclasses.field(
24
default_factory=lambda: themes.theme(accent_color="blue")
25
)
26
27
# The global style for the app
28
style: ComponentStyle = dataclasses.field(default_factory=dict)
29
30
# A list of URLs to stylesheets to include in the app
31
stylesheets: list[str] = dataclasses.field(default_factory=list)
32
33
# Whether to include CSS reset for margin and padding
34
reset_style: bool = dataclasses.field(default=True)
35
36
# A component that is present on every page
37
overlay_component: Component | ComponentCallable | None = dataclasses.field(
38
default=None
39
)
40
41
# Components to add to the head of every page
42
head_components: list[Component] = dataclasses.field(default_factory=list)
43
44
# The language to add to the html root tag of every page
45
html_lang: str | None = None
46
47
# Attributes to add to the html root tag of every page
48
html_custom_attrs: dict[str, str] | None = None
49
50
# Whether to enable state for the app
51
enable_state: bool = True
52
53
# Admin dashboard to view and manage the database
54
admin_dash: AdminDash | None = None
55
56
def add_page(
57
self,
58
component: Component | ComponentCallable,
59
route: str | None = None,
60
title: str | Var | None = None,
61
description: str | Var | None = None,
62
image: str | None = None,
63
meta: Sequence[Mapping[str, str]] | None = None,
64
on_load: EventType[()] | None = None
65
) -> None:
66
"""
67
Add a page to the application with routing and metadata.
68
69
Args:
70
component: Component function or instance to render
71
route: URL route path (defaults to function name)
72
title: Page title for SEO and browser tabs (can be Var for dynamic titles)
73
description: Page description for SEO meta tags (can be Var for dynamic descriptions)
74
image: Page image URL for social media sharing
75
meta: Additional HTML meta tags as sequence of mappings
76
on_load: Event handler(s) to execute when page loads
77
"""
78
...
79
80
def compile(self, force_compile: bool = False) -> None:
81
"""
82
Compile the application to React components.
83
84
Args:
85
force_compile: Whether to force recompilation even if no changes detected
86
"""
87
...
88
89
def __call__(self) -> ASGIApp:
90
"""
91
Get the ASGI app instance.
92
93
Returns:
94
The ASGI app for serving the application
95
"""
96
...
97
```
98
99
### Reactive State Management
100
101
The State system provides reactive state management with automatic frontend synchronization, computed variables, and type-safe state updates.
102
103
```python { .api }
104
class BaseState(EvenMoreBasicBaseState):
105
"""
106
The core state class that all Reflex states inherit from.
107
108
Provides reactive state management with automatic frontend synchronization,
109
event handling, and state hierarchy management.
110
111
All user state classes should inherit from this class either directly
112
or through the State alias.
113
"""
114
115
# Class-level variable tracking
116
vars: ClassVar[dict[str, Var]] = {}
117
base_vars: ClassVar[dict[str, Var]] = {}
118
computed_vars: ClassVar[dict[str, ComputedVar]] = {}
119
inherited_vars: ClassVar[dict[str, Var]] = {}
120
backend_vars: ClassVar[dict[str, Var]] = {}
121
122
@classmethod
123
def get_parent_state(cls) -> type[BaseState] | None:
124
"""
125
Get the parent state class.
126
127
Returns:
128
The parent state class or None if this is a root state
129
130
Raises:
131
ValueError: If more than one parent state is found
132
"""
133
...
134
135
@classmethod
136
def get_root_state(cls) -> type[BaseState]:
137
"""
138
Get the root state class in the state hierarchy.
139
140
Returns:
141
The root state class
142
"""
143
...
144
145
@classmethod
146
def get_substates(cls) -> set[type[BaseState]]:
147
"""
148
Get all substate classes that inherit from this state.
149
150
Returns:
151
Set of substate classes
152
"""
153
...
154
155
@classmethod
156
def get_class_substate(cls, path: Sequence[str] | str) -> type[BaseState]:
157
"""
158
Get a substate class by path.
159
160
Args:
161
path: The path to the substate (dot-separated string or sequence)
162
163
Returns:
164
The substate class
165
"""
166
...
167
168
def get_substate(self, path: Sequence[str]) -> BaseState:
169
"""
170
Get a substate instance by path.
171
172
Args:
173
path: The path to the substate
174
175
Returns:
176
The substate instance
177
"""
178
...
179
180
async def get_state(self, state_cls: type[T_STATE]) -> T_STATE:
181
"""
182
Get an instance of another state class associated with this token.
183
184
Args:
185
state_cls: The state class to get an instance of
186
187
Returns:
188
Instance of the requested state class
189
"""
190
...
191
192
async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE:
193
"""
194
Get the value of a Var from another state.
195
196
Args:
197
var: The var to get the value for
198
199
Returns:
200
The current value of the var
201
"""
202
...
203
204
def get_delta(self) -> Delta:
205
"""
206
Get the state changes (delta) since last sync.
207
208
Returns:
209
Dictionary of changed state variables
210
"""
211
...
212
213
def get_value(self, key: str) -> Any:
214
"""
215
Get the value of a state field without proxying.
216
217
Args:
218
key: The field name
219
220
Returns:
221
The field value
222
"""
223
...
224
225
class State(BaseState):
226
"""
227
The app base state class - alias for BaseState.
228
229
This is the main state class that user applications should inherit from.
230
Includes hydration state tracking for client-server synchronization.
231
"""
232
233
# Whether the state has been hydrated on the frontend
234
is_hydrated: bool = False
235
236
@event
237
def set_is_hydrated(self, value: bool) -> None:
238
"""
239
Set the hydrated state.
240
241
Args:
242
value: The hydrated state
243
"""
244
...
245
246
class ComponentState(State, mixin=True):
247
"""
248
Base class for component-level state management.
249
250
Allows creation of a state instance per component, enabling
251
bundling of UI and state logic into a single class where each
252
instance has separate state.
253
254
Subclass this and define a get_component method that returns
255
the UI for the component instance.
256
"""
257
258
@classmethod
259
def get_component(cls, *children, **props) -> Component:
260
"""
261
Get the component instance for this state.
262
263
Args:
264
children: The children of the component
265
props: The props of the component
266
267
Returns:
268
The component instance
269
"""
270
...
271
```
272
273
### Computed Variables
274
275
Reactive computed properties that automatically update when dependent state changes, with caching and dependency tracking.
276
277
```python { .api }
278
@computed_var
279
def computed_property(self) -> ReturnType:
280
"""
281
Decorator for creating computed state variables.
282
283
Computed variables automatically recalculate when their dependencies
284
change and are cached until dependencies update.
285
286
Returns:
287
Computed value based on current state
288
"""
289
...
290
291
def var(func: Callable) -> ComputedVar:
292
"""
293
Alias for computed_var decorator.
294
295
Args:
296
func: Function to convert to computed variable
297
298
Returns:
299
ComputedVar instance with automatic dependency tracking
300
"""
301
...
302
303
def dynamic(func: Callable) -> DynamicRouteVar:
304
"""
305
Create dynamic route argument handler.
306
307
Args:
308
func: Function that processes dynamic route arguments
309
310
Returns:
311
DynamicRouteVar for handling URL parameters
312
"""
313
...
314
```
315
316
### Page Routing
317
318
Declarative page routing with metadata support, SEO optimization, and automatic route generation from component functions.
319
320
```python { .api }
321
def page(
322
route: str | None = None,
323
title: str | None = None,
324
image: str | None = None,
325
description: str | None = None,
326
meta: list[dict] | None = None,
327
script_tags: list[dict] | None = None,
328
on_load: EventType | None = None
329
) -> Callable:
330
"""
331
Decorator for registering component functions as pages.
332
333
Automatically registers decorated functions with the app when
334
App.compile() is called, enabling clean route definition.
335
336
Args:
337
route: URL route path (defaults to function name)
338
title: Page title for browser tabs and SEO
339
image: Favicon or social media image URL
340
description: Meta description for SEO
341
meta: Additional HTML meta tags
342
script_tags: Custom script tags for the page
343
on_load: Event handlers to execute on page load
344
345
Returns:
346
Decorated function with page registration metadata
347
"""
348
...
349
```
350
351
Usage example:
352
353
```python
354
@rx.page(route="/dashboard", title="User Dashboard", on_load=State.load_user_data)
355
def dashboard():
356
return rx.vstack(
357
rx.heading("Dashboard"),
358
rx.text(f"Welcome, {State.username}"),
359
)
360
```
361
362
### Application Configuration
363
364
Comprehensive configuration management for database connections, styling, deployment settings, and development options.
365
366
```python { .api }
367
class Config:
368
"""
369
Application configuration management.
370
371
Centralizes settings for database, styling, deployment, and
372
development options with environment variable support.
373
"""
374
375
app_name: str
376
"""Application name used for compilation and deployment."""
377
378
db_url: str | None = None
379
"""Database connection URL (PostgreSQL, SQLite, etc.)."""
380
381
redis_url: str | None = None
382
"""Redis URL for session storage and caching."""
383
384
frontend_port: int = 3000
385
"""Port for the frontend development server."""
386
387
backend_port: int = 8000
388
"""Port for the backend API server."""
389
390
deploy_url: str | None = None
391
"""Base URL for production deployment."""
392
393
env: str = "dev"
394
"""Environment setting: 'dev', 'prod', or custom."""
395
396
tailwind: dict | None = None
397
"""Tailwind CSS configuration overrides."""
398
399
def __init__(self, **kwargs) -> None:
400
"""
401
Initialize configuration with optional overrides.
402
403
Args:
404
**kwargs: Configuration values to override defaults
405
"""
406
...
407
408
class DBConfig:
409
"""
410
Database configuration with PostgreSQL optimization.
411
412
Provides database connection management, migration settings,
413
and engine configuration for SQLAlchemy integration.
414
"""
415
416
db_url: str
417
"""Database connection URL."""
418
419
engine: Engine | None = None
420
"""SQLAlchemy engine instance (auto-created if None)."""
421
422
migrate: bool = True
423
"""Whether to run database migrations on startup."""
424
425
pool_size: int = 10
426
"""Connection pool size for database connections."""
427
428
max_overflow: int = 20
429
"""Maximum overflow connections beyond pool_size."""
430
431
def __init__(self, db_url: str, **kwargs) -> None:
432
"""
433
Initialize database configuration.
434
435
Args:
436
db_url: Database connection URL
437
**kwargs: Additional configuration options
438
"""
439
...
440
```
441
442
### File Upload Support
443
444
Built-in file upload handling with validation, storage management, and progress tracking for web applications.
445
446
```python { .api }
447
class UploadFile:
448
"""
449
File upload handling with validation and storage.
450
451
Represents an uploaded file with metadata, validation,
452
and storage utilities for processing user uploads.
453
"""
454
455
filename: str
456
"""Original filename from the client."""
457
458
content_type: str
459
"""MIME type of the uploaded file."""
460
461
size: int
462
"""File size in bytes."""
463
464
file: BinaryIO
465
"""File-like object for reading file contents."""
466
467
def read(self) -> bytes:
468
"""
469
Read the complete file contents.
470
471
Returns:
472
Complete file contents as bytes
473
"""
474
...
475
476
def save(self, path: str) -> None:
477
"""
478
Save the file to a specified path.
479
480
Args:
481
path: File system path to save the file
482
"""
483
...
484
```
485
486
## Types
487
488
```python { .api }
489
from typing import Any, Callable, Dict, List, Optional, Union
490
from datetime import datetime
491
from sqlalchemy import Engine
492
493
# Core Application Types
494
Component = Any # Reflex component instance
495
EventType = Callable | EventHandler | list[EventHandler] # Event handler types
496
497
# State Types
498
Delta = Dict[str, Any] # State change dictionary
499
StateUpdate = Dict[str, Any] # State update payload
500
501
# Configuration Types
502
class RouterData:
503
"""Router data with current page information."""
504
path: str
505
query: Dict[str, str]
506
headers: Dict[str, str]
507
session_id: str
508
509
# Variable Types
510
ComputedVar = Any # Computed reactive variable
511
DynamicRouteVar = Any # Dynamic route parameter variable
512
513
# File Types
514
from typing import BinaryIO
515
FileUpload = BinaryIO | UploadFile
516
```