Web apps in pure Python with reactive components and automatic frontend generation.
npx @tessl/cli install tessl/pypi-reflex@0.8.00
# Reflex
1
2
Web apps in pure Python with reactive components and automatic frontend generation. Reflex enables building full-stack web applications entirely in Python, compiling to React components with automatic state synchronization between frontend and backend.
3
4
## Package Information
5
6
- **Package Name**: reflex
7
- **Language**: Python
8
- **Installation**: `pip install reflex`
9
10
## Core Imports
11
12
```python
13
import reflex as rx
14
```
15
16
Common state and component patterns:
17
18
```python
19
from reflex import State, Component, Var
20
```
21
22
## Basic Usage
23
24
```python
25
import reflex as rx
26
27
# Define application state
28
class State(rx.State):
29
count: int = 0
30
31
def increment(self):
32
self.count += 1
33
34
def decrement(self):
35
self.count -= 1
36
37
# Create a page component
38
def index():
39
return rx.center(
40
rx.vstack(
41
rx.heading("Counter App", size="lg"),
42
rx.heading(State.count, size="md"),
43
rx.hstack(
44
rx.button("Decrement", on_click=State.decrement),
45
rx.button("Increment", on_click=State.increment),
46
),
47
spacing="4",
48
),
49
height="100vh",
50
)
51
52
# Create and configure the app
53
app = rx.App()
54
app.add_page(index)
55
56
if __name__ == "__main__":
57
app.compile()
58
```
59
60
## Architecture
61
62
Reflex follows a reactive architecture with clear separation of concerns:
63
64
- **App**: Top-level application container managing pages, routing, and configuration
65
- **State**: Reactive state management with automatic frontend synchronization
66
- **Components**: Declarative UI components based on Radix UI with full Python interface
67
- **Events**: Type-safe event handling between frontend interactions and backend state changes
68
- **Pages**: Route-based page system with SEO support and metadata management
69
70
The framework compiles Python components to React, handles state synchronization via WebSocket, and provides a complete full-stack development experience without requiring JavaScript knowledge.
71
72
## Capabilities
73
74
### Core Framework
75
76
Application management, reactive state, page routing, and configuration system. Provides the foundation for building full-stack web applications with automatic frontend generation.
77
78
```python { .api }
79
@dataclasses.dataclass()
80
class App(MiddlewareMixin, LifespanMixin):
81
"""Main application class for creating Reflex apps."""
82
theme: Component | None = dataclasses.field(
83
default_factory=lambda: themes.theme(accent_color="blue")
84
)
85
style: ComponentStyle = dataclasses.field(default_factory=dict)
86
stylesheets: list[str] = dataclasses.field(default_factory=list)
87
enable_state: bool = True
88
89
def add_page(
90
self,
91
component: Component | ComponentCallable,
92
route: str | None = None,
93
title: str | Var | None = None,
94
description: str | Var | None = None,
95
image: str | None = None,
96
meta: Sequence[Mapping[str, str]] | None = None,
97
on_load: EventType[()] | None = None
98
) -> None: ...
99
def compile(self, force_compile: bool = False) -> None: ...
100
def __call__(self) -> ASGIApp: ...
101
102
class BaseState(EvenMoreBasicBaseState):
103
"""The core state class that all Reflex states inherit from."""
104
@classmethod
105
def get_parent_state(cls) -> type[BaseState] | None: ...
106
@classmethod
107
def get_substates(cls) -> set[type[BaseState]]: ...
108
def get_substate(self, path: Sequence[str]) -> BaseState: ...
109
async def get_state(self, state_cls: type[T_STATE]) -> T_STATE: ...
110
111
class State(BaseState):
112
"""The app base state class - alias for BaseState."""
113
is_hydrated: bool = False
114
115
@event
116
def set_is_hydrated(self, value: bool) -> None: ...
117
118
@page(route: str | None = None, title: str | None = None, **kwargs)
119
def page_decorator(func: Callable) -> Callable: ...
120
121
class Config:
122
"""Application configuration management."""
123
app_name: str
124
db_url: str | None = None
125
redis_url: str | None = None
126
tailwind: dict | None = None
127
```
128
129
[Core Framework](./core-framework.md)
130
131
### UI Components
132
133
60+ Radix UI-based components including layout containers, typography, forms, interactive elements, and data display. All components are fully typed and provide comprehensive styling options.
134
135
```python { .api }
136
# Layout Components
137
def box(*children, **props) -> Component: ...
138
def flex(*children, direction: str = "row", **props) -> Component: ...
139
def vstack(*children, spacing: str = "2", **props) -> Component: ...
140
def hstack(*children, spacing: str = "2", **props) -> Component: ...
141
142
# Typography
143
def heading(*children, size: str = "4", **props) -> Component: ...
144
def text(*children, size: str = "2", **props) -> Component: ...
145
146
# Form Components
147
def button(*children, variant: str = "solid", **props) -> Component: ...
148
def input(placeholder: str = "", **props) -> Component: ...
149
def text_area(placeholder: str = "", **props) -> Component: ...
150
151
# Interactive Components
152
def dialog(*children, **props) -> Component: ...
153
def popover(*children, **props) -> Component: ...
154
def tooltip(*children, **props) -> Component: ...
155
```
156
157
[UI Components](./ui-components.md)
158
159
### Event System
160
161
Type-safe event handling connecting frontend interactions to backend state changes. Supports synchronous and asynchronous event handlers with automatic state synchronization.
162
163
```python { .api }
164
class EventHandler:
165
"""Core event handler implementation."""
166
fn: Callable
167
args: tuple
168
kwargs: dict
169
170
def event(fn: Callable) -> EventHandler: ...
171
172
# Event Actions
173
def redirect(path: str | Var[str], is_external: bool = False, replace: bool = False) -> EventSpec: ...
174
def console_log(message: str | Var[str]) -> EventSpec: ...
175
def download(url: str | Var | None = None, filename: str | Var | None = None, data: str | bytes | Var | None = None) -> EventSpec: ...
176
def set_clipboard(content: str | Var[str]) -> EventSpec: ...
177
def window_alert(message: str | Var[str]) -> EventSpec: ...
178
def scroll_to(elem_id: str, align_to_top: bool | Var[bool] = True) -> EventSpec: ...
179
```
180
181
[Event System](./event-system.md)
182
183
### Database & Models
184
185
SQLAlchemy-based database integration with automatic migrations, session management, and async support. Includes built-in PostgreSQL configuration and model relationships.
186
187
```python { .api }
188
class Model(Base, sqlmodel.SQLModel):
189
"""Base class to define a table in the database."""
190
id: int | None = sqlmodel.Field(default=None, primary_key=True)
191
192
def __init_subclass__(cls): ...
193
def dict(self, **kwargs): ...
194
195
class ModelRegistry:
196
"""Registry for all models in the application."""
197
models: ClassVar[set[SQLModelOrSqlAlchemy]] = set()
198
199
@classmethod
200
def register(cls, model: SQLModelOrSqlAlchemy): ...
201
202
def session() -> Session: ...
203
def asession() -> AsyncSession: ...
204
205
class DBConfig:
206
"""Database configuration with PostgreSQL support."""
207
db_url: str
208
engine: Engine | None = None
209
migrate: bool = True
210
```
211
212
[Database & Models](./database-models.md)
213
214
### Styling & Theming
215
216
Comprehensive styling system with CSS-in-Python, responsive design, color modes, and Radix UI theming. Supports custom themes, breakpoints, and design tokens.
217
218
```python { .api }
219
class Style:
220
"""CSS styling management with responsive support."""
221
def __init__(self, **kwargs) -> None: ...
222
223
def theme(
224
accent_color: str = "indigo",
225
gray_color: str = "gray",
226
radius: str = "medium",
227
**props
228
) -> Component: ...
229
230
def color_mode() -> Component: ...
231
def toggle_color_mode() -> EventHandler: ...
232
233
# Responsive Components
234
def desktop_only(*children) -> Component: ...
235
def mobile_only(*children) -> Component: ...
236
def tablet_only(*children) -> Component: ...
237
```
238
239
[Styling & Theming](./styling-theming.md)
240
241
### Advanced Features
242
243
File uploads, testing framework, middleware system, admin dashboard, and experimental features for complex applications.
244
245
```python { .api }
246
class UploadFile:
247
"""File upload handling with validation and storage."""
248
filename: str
249
content_type: str
250
size: int
251
252
def upload(*children, **props) -> Component: ...
253
def middleware(func: Callable) -> Callable: ...
254
255
class AdminDash:
256
"""Admin dashboard configuration and management."""
257
def __init__(self, models: list[type[Model]] = None) -> None: ...
258
```
259
260
[Advanced Features](./advanced-features.md)
261
262
## Types
263
264
```python { .api }
265
from typing import Any, Callable, Dict, List, Optional, Union
266
from reflex.vars.base import Var
267
268
# Core Types
269
Component = Any # Component instance
270
EventType = Callable | EventHandler | list[EventHandler]
271
Props = Dict[str, Any]
272
273
# Variable Types
274
Var[T] = Any # Reactive variable of type T
275
ComputedVar[T] = Any # Computed reactive variable
276
277
# State Types
278
Delta = Dict[str, Any] # State change delta
279
StateUpdate = Dict[str, Any] # State update payload
280
281
# Event Types
282
class Event:
283
token: str
284
name: str
285
router_data: Dict[str, Any]
286
payload: Dict[str, Any]
287
288
# Storage Types
289
class Cookie:
290
name: str
291
value: str
292
max_age: int | None = None
293
294
class LocalStorage:
295
key: str
296
value: Any
297
298
class SessionStorage:
299
key: str
300
value: Any
301
```