or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcore-framework.mddatabase-models.mdevent-system.mdindex.mdstyling-theming.mdui-components.md

advanced-features.mddocs/

0

# Advanced Features

1

2

File uploads, testing framework, middleware system, admin dashboard, data visualization, and experimental features for building sophisticated web applications with enterprise-grade capabilities.

3

4

## Capabilities

5

6

### File Upload System

7

8

Comprehensive file upload handling with progress tracking, validation, storage management, and security features for robust file processing.

9

10

```python { .api }

11

def upload(

12

*children,

13

id: str = "",

14

multiple: bool = False,

15

accept: list[str] = None,

16

max_files: int = 1,

17

max_file_size: int = 100 * 1024 * 1024, # 100MB

18

disabled: bool = False,

19

**props

20

) -> Component:

21

"""

22

File upload component with drag-and-drop support and validation.

23

24

Provides comprehensive file upload interface with progress tracking,

25

validation, and integration with backend file processing.

26

27

Args:

28

*children: Upload area content (dropzone, buttons, etc.)

29

id: Unique identifier for upload session

30

multiple: Whether to allow multiple file selection

31

accept: List of accepted file types (MIME types or extensions)

32

max_files: Maximum number of files allowed

33

max_file_size: Maximum file size in bytes per file

34

disabled: Whether upload is currently disabled

35

**props: Additional component styling and configuration

36

37

Returns:

38

File upload component with drag-and-drop functionality

39

"""

40

...

41

42

class UploadFile:

43

"""

44

Uploaded file representation with metadata and processing utilities.

45

46

Represents a file uploaded through the Reflex upload system with

47

complete metadata, validation results, and storage utilities.

48

"""

49

50

filename: str

51

"""Original filename from client."""

52

53

content_type: str

54

"""MIME type of the uploaded file."""

55

56

size: int

57

"""File size in bytes."""

58

59

file: BinaryIO

60

"""File-like object for reading content."""

61

62

upload_id: str

63

"""Unique identifier for this upload session."""

64

65

def read(self, size: int = -1) -> bytes:

66

"""

67

Read file content with optional size limit.

68

69

Args:

70

size: Number of bytes to read (-1 for all)

71

72

Returns:

73

File content as bytes

74

"""

75

...

76

77

def save(self, path: str) -> None:

78

"""

79

Save file to specified filesystem path.

80

81

Args:

82

path: Target filesystem path for saving

83

"""

84

...

85

86

def validate(self, rules: dict) -> dict:

87

"""

88

Validate file against specified rules.

89

90

Args:

91

rules: Validation rules (size, type, etc.)

92

93

Returns:

94

Dictionary with validation results

95

"""

96

...

97

98

# Upload utility functions

99

def get_upload_dir() -> str:

100

"""

101

Get configured upload directory path.

102

103

Returns:

104

Absolute path to upload directory

105

"""

106

...

107

108

def get_upload_url(filename: str, upload_id: str = "") -> str:

109

"""

110

Get URL for accessing uploaded file.

111

112

Args:

113

filename: Name of uploaded file

114

upload_id: Upload session identifier

115

116

Returns:

117

URL for accessing the uploaded file

118

"""

119

...

120

121

def selected_files(upload_id: str = "") -> list[str]:

122

"""

123

Get list of selected files for upload session.

124

125

Args:

126

upload_id: Upload session identifier

127

128

Returns:

129

List of selected filenames

130

"""

131

...

132

133

def clear_selected_files(upload_id: str = "") -> EventHandler:

134

"""

135

Clear selected files from upload session.

136

137

Args:

138

upload_id: Upload session to clear

139

140

Returns:

141

EventHandler that clears selected files

142

"""

143

...

144

145

def cancel_upload(upload_id: str = "") -> EventHandler:

146

"""

147

Cancel ongoing file upload operation.

148

149

Args:

150

upload_id: Upload session to cancel

151

152

Returns:

153

EventHandler that cancels upload

154

"""

155

...

156

```

157

158

File upload usage example:

159

160

```python

161

class FileUploadState(rx.State):

162

uploaded_files: list[str] = []

163

164

async def handle_upload(self, files: list[rx.UploadFile]):

165

for file in files:

166

# Validate file

167

if file.size > 10 * 1024 * 1024: # 10MB limit

168

continue

169

170

# Save file

171

upload_path = f"./uploads/{file.filename}"

172

file.save(upload_path)

173

self.uploaded_files.append(file.filename)

174

175

def file_upload_demo():

176

return rx.vstack(

177

rx.upload(

178

rx.vstack(

179

rx.button("Select Files", color_scheme="blue"),

180

rx.text("Or drag and drop files here"),

181

align="center",

182

spacing="2"

183

),

184

id="file-upload",

185

multiple=True,

186

accept=[".pdf", ".jpg", ".png", ".doc"],

187

max_files=5,

188

max_file_size=10 * 1024 * 1024,

189

on_upload=FileUploadState.handle_upload

190

),

191

rx.foreach(

192

FileUploadState.uploaded_files,

193

lambda filename: rx.text(f"Uploaded: {filename}")

194

)

195

)

196

```

197

198

### Middleware System

199

200

Request/response processing middleware for authentication, logging, CORS, rate limiting, and custom request handling.

201

202

```python { .api }

203

def middleware(func: Callable) -> Callable:

204

"""

205

Decorator for creating middleware functions.

206

207

Middleware functions process requests and responses, enabling

208

cross-cutting concerns like authentication, logging, and validation.

209

210

Args:

211

func: Function to convert to middleware

212

213

Returns:

214

Middleware function that processes requests/responses

215

"""

216

...

217

218

class Middleware:

219

"""

220

Base middleware class for request processing.

221

222

Provides hooks for request preprocessing, response postprocessing,

223

and error handling in the request lifecycle.

224

"""

225

226

def __init__(self, **config) -> None:

227

"""

228

Initialize middleware with configuration.

229

230

Args:

231

**config: Middleware-specific configuration options

232

"""

233

...

234

235

async def preprocess(self, request: Request) -> Request | Response:

236

"""

237

Process request before it reaches route handler.

238

239

Args:

240

request: Incoming HTTP request

241

242

Returns:

243

Modified request or early response

244

"""

245

...

246

247

async def postprocess(self, request: Request, response: Response) -> Response:

248

"""

249

Process response before sending to client.

250

251

Args:

252

request: Original HTTP request

253

response: Response from route handler

254

255

Returns:

256

Modified response

257

"""

258

...

259

260

async def on_error(self, request: Request, error: Exception) -> Response:

261

"""

262

Handle errors that occur during request processing.

263

264

Args:

265

request: HTTP request that caused error

266

error: Exception that occurred

267

268

Returns:

269

Error response to send to client

270

"""

271

...

272

```

273

274

Middleware examples:

275

276

```python

277

# Authentication middleware

278

@rx.middleware

279

async def auth_middleware(request: Request, call_next):

280

# Check for authentication token

281

token = request.headers.get("Authorization")

282

if not token and request.url.path.startswith("/api/protected"):

283

return Response({"error": "Authentication required"}, status_code=401)

284

285

response = await call_next(request)

286

return response

287

288

# Logging middleware

289

@rx.middleware

290

async def logging_middleware(request: Request, call_next):

291

start_time = time.time()

292

293

response = await call_next(request)

294

295

duration = time.time() - start_time

296

print(f"{request.method} {request.url.path} - {response.status_code} - {duration:.3f}s")

297

298

return response

299

300

# CORS middleware

301

@rx.middleware

302

async def cors_middleware(request: Request, call_next):

303

response = await call_next(request)

304

response.headers["Access-Control-Allow-Origin"] = "*"

305

response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE"

306

response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"

307

return response

308

```

309

310

### Testing Framework

311

312

Comprehensive testing utilities for component testing, state management validation, and end-to-end application testing.

313

314

```python { .api }

315

# Testing module - accessible as rx.testing

316

import reflex.testing as testing

317

318

class TestClient:

319

"""

320

Test client for simulating HTTP requests and testing routes.

321

322

Provides utilities for testing Reflex applications including

323

state management, component rendering, and API endpoints.

324

"""

325

326

def __init__(self, app: App) -> None:

327

"""

328

Initialize test client with Reflex app.

329

330

Args:

331

app: Reflex application instance to test

332

"""

333

...

334

335

def get(self, path: str, **kwargs) -> TestResponse:

336

"""

337

Simulate GET request to application route.

338

339

Args:

340

path: Route path to request

341

**kwargs: Additional request parameters

342

343

Returns:

344

Test response with status, content, and metadata

345

"""

346

...

347

348

def post(self, path: str, data: dict = None, **kwargs) -> TestResponse:

349

"""

350

Simulate POST request with data.

351

352

Args:

353

path: Route path for POST request

354

data: Request payload data

355

**kwargs: Additional request parameters

356

357

Returns:

358

Test response from POST request

359

"""

360

...

361

362

def trigger_event(self, event_name: str, payload: dict = None) -> None:

363

"""

364

Trigger state event for testing event handlers.

365

366

Args:

367

event_name: Name of event to trigger

368

payload: Event payload data

369

"""

370

...

371

372

class ComponentTester:

373

"""

374

Utilities for testing individual components and their behavior.

375

"""

376

377

@staticmethod

378

def render(component: Component) -> dict:

379

"""

380

Render component to testable representation.

381

382

Args:

383

component: Component instance to render

384

385

Returns:

386

Dictionary representation of rendered component

387

"""

388

...

389

390

@staticmethod

391

def find_by_text(rendered: dict, text: str) -> dict | None:

392

"""

393

Find component containing specific text.

394

395

Args:

396

rendered: Rendered component representation

397

text: Text content to search for

398

399

Returns:

400

Component containing text or None

401

"""

402

...

403

404

@staticmethod

405

def find_by_id(rendered: dict, id: str) -> dict | None:

406

"""

407

Find component by ID attribute.

408

409

Args:

410

rendered: Rendered component representation

411

id: Component ID to search for

412

413

Returns:

414

Component with matching ID or None

415

"""

416

...

417

418

class StateTester:

419

"""

420

Utilities for testing state management and event handlers.

421

"""

422

423

@staticmethod

424

def create_state(state_class: type[State], **initial) -> State:

425

"""

426

Create state instance for testing.

427

428

Args:

429

state_class: State class to instantiate

430

**initial: Initial state values

431

432

Returns:

433

State instance with test configuration

434

"""

435

...

436

437

@staticmethod

438

def trigger_event(state: State, method: str, *args, **kwargs) -> dict:

439

"""

440

Trigger state method and return resulting state changes.

441

442

Args:

443

state: State instance to test

444

method: Method name to trigger

445

*args: Method arguments

446

**kwargs: Method keyword arguments

447

448

Returns:

449

Dictionary of state changes from event

450

"""

451

...

452

```

453

454

Testing examples:

455

456

```python

457

import pytest

458

import reflex as rx

459

460

# Component testing

461

def test_button_component():

462

button = rx.button("Click me", on_click=lambda: None)

463

rendered = rx.testing.ComponentTester.render(button)

464

465

assert rendered["tag"] == "Button"

466

assert "Click me" in rendered["children"]

467

468

# State testing

469

def test_counter_state():

470

state = rx.testing.StateTester.create_state(CounterState, count=0)

471

472

# Test increment

473

changes = rx.testing.StateTester.trigger_event(state, "increment")

474

assert changes["count"] == 1

475

476

# Test decrement

477

changes = rx.testing.StateTester.trigger_event(state, "decrement")

478

assert changes["count"] == 0

479

480

# Integration testing

481

def test_app_routes():

482

app = rx.App()

483

client = rx.testing.TestClient(app)

484

485

response = client.get("/")

486

assert response.status_code == 200

487

488

response = client.post("/api/data", data={"key": "value"})

489

assert response.status_code == 201

490

```

491

492

### Admin Dashboard

493

494

Built-in admin interface for managing database models, monitoring application metrics, and performing administrative tasks.

495

496

```python { .api }

497

class AdminDash:

498

"""

499

Admin dashboard configuration and management.

500

501

Provides web-based admin interface for managing database models,

502

monitoring application performance, and administrative tasks.

503

"""

504

505

def __init__(

506

self,

507

models: list[type[Model]] = None,

508

path: str = "/admin",

509

title: str = "Admin Dashboard"

510

) -> None:

511

"""

512

Initialize admin dashboard with model configuration.

513

514

Args:

515

models: List of database models to include in admin

516

path: URL path for admin interface

517

title: Dashboard title and branding

518

"""

519

...

520

521

def add_model(self, model: type[Model], **config) -> None:

522

"""

523

Add database model to admin interface.

524

525

Args:

526

model: Model class to add

527

**config: Model-specific admin configuration

528

"""

529

...

530

531

def add_view(self, path: str, component: Component, **config) -> None:

532

"""

533

Add custom admin view.

534

535

Args:

536

path: URL path for custom view

537

component: Component to render for view

538

**config: View configuration options

539

"""

540

...

541

542

def configure_permissions(self, rules: dict) -> None:

543

"""

544

Configure admin access permissions.

545

546

Args:

547

rules: Permission rules for admin access

548

"""

549

...

550

```

551

552

Admin dashboard usage:

553

554

```python

555

# Configure admin dashboard

556

admin = rx.AdminDash(

557

models=[User, Post, Tag],

558

path="/admin",

559

title="My App Admin"

560

)

561

562

# Add to application

563

app = rx.App()

564

admin.register(app)

565

566

# Custom admin views

567

@admin.view("/stats", title="Statistics")

568

def admin_stats():

569

return rx.vstack(

570

rx.heading("Application Statistics"),

571

rx.stat_group(

572

rx.stat(label="Total Users", value=User.count()),

573

rx.stat(label="Total Posts", value=Post.count()),

574

)

575

)

576

```

577

578

### Data Visualization

579

580

Integration with popular charting libraries for data visualization including Plotly, Recharts, and custom chart components.

581

582

```python { .api }

583

def plotly(*children, figure: dict = None, **props) -> Component:

584

"""

585

Plotly chart integration for interactive data visualization.

586

587

Renders Plotly charts with full interactivity, zoom, pan,

588

and export capabilities for sophisticated data visualization.

589

590

Args:

591

*children: Chart content (usually empty for Plotly)

592

figure: Plotly figure dictionary with data and layout

593

**props: Chart configuration and styling options

594

595

Returns:

596

Interactive Plotly chart component

597

"""

598

...

599

600

def data_table(

601

data: list[dict] = None,

602

columns: list[dict] = None,

603

pagination: bool = True,

604

search: bool = True,

605

sort: bool = True,

606

**props

607

) -> Component:

608

"""

609

Advanced data table with GridJS integration.

610

611

Provides feature-rich data table with sorting, filtering,

612

pagination, and export capabilities for large datasets.

613

614

Args:

615

data: List of row data as dictionaries

616

columns: Column configuration with headers and formatting

617

pagination: Whether to enable pagination

618

search: Whether to enable search functionality

619

sort: Whether to enable column sorting

620

**props: Table styling and configuration options

621

622

Returns:

623

Advanced data table component with interactive features

624

"""

625

...

626

627

def data_editor(

628

data: list[dict] = None,

629

columns: list[dict] = None,

630

editable: bool = True,

631

**props

632

) -> Component:

633

"""

634

Interactive data grid editor for spreadsheet-like data editing.

635

636

Args:

637

data: Grid data as list of row dictionaries

638

columns: Column definitions with types and formatting

639

editable: Whether cells can be edited inline

640

**props: Grid configuration and styling

641

642

Returns:

643

Interactive data grid editor component

644

"""

645

...

646

647

class data_editor_theme:

648

"""Theme configuration for data editor component."""

649

650

def __init__(

651

self,

652

accent_color: str = "blue",

653

font_family: str = "system-ui",

654

**kwargs

655

) -> None:

656

"""

657

Configure data editor theme.

658

659

Args:

660

accent_color: Primary theme color

661

font_family: Font family for grid text

662

**kwargs: Additional theme options

663

"""

664

...

665

```

666

667

Data visualization examples:

668

669

```python

670

# Plotly chart

671

def sales_chart():

672

figure = {

673

"data": [

674

{

675

"x": ["Jan", "Feb", "Mar", "Apr", "May"],

676

"y": [20, 14, 23, 25, 22],

677

"type": "scatter",

678

"mode": "lines+markers",

679

"name": "Sales"

680

}

681

],

682

"layout": {

683

"title": "Monthly Sales",

684

"xaxis": {"title": "Month"},

685

"yaxis": {"title": "Sales ($1000)"}

686

}

687

}

688

return rx.plotly(figure=figure)

689

690

# Data table

691

def user_table():

692

return rx.data_table(

693

data=[

694

{"name": "John", "email": "john@example.com", "age": 30},

695

{"name": "Jane", "email": "jane@example.com", "age": 25},

696

],

697

columns=[

698

{"field": "name", "header": "Name", "sortable": True},

699

{"field": "email", "header": "Email"},

700

{"field": "age", "header": "Age", "type": "number"}

701

],

702

pagination=True,

703

search=True

704

)

705

```

706

707

### Utility Components

708

709

Specialized components for enhanced user experience including notifications, content rendering, and interactive elements.

710

711

```python { .api }

712

def toast(*children, **props) -> Component:

713

"""

714

Toast notification system with multiple variants and positioning.

715

716

Provides non-intrusive notifications with automatic dismissal,

717

action buttons, and consistent positioning across the application.

718

719

Args:

720

*children: Toast content (text, icons, buttons)

721

**props: Toast configuration (variant, position, duration)

722

723

Returns:

724

Toast notification component

725

"""

726

...

727

728

def markdown(content: str, **props) -> Component:

729

"""

730

Markdown content rendering with syntax highlighting.

731

732

Renders Markdown content with support for code blocks,

733

tables, links, and custom styling integration.

734

735

Args:

736

content: Markdown content string to render

737

**props: Markdown renderer configuration

738

739

Returns:

740

Rendered Markdown content component

741

"""

742

...

743

744

def code_block(

745

code: str = "",

746

language: str = "python",

747

theme: str = "default",

748

**props

749

) -> Component:

750

"""

751

Syntax-highlighted code block for documentation and examples.

752

753

Args:

754

code: Source code content to display

755

language: Programming language for syntax highlighting

756

theme: Color theme for syntax highlighting

757

**props: Code block styling options

758

759

Returns:

760

Syntax-highlighted code block component

761

"""

762

...

763

764

def logo(**props) -> Component:

765

"""

766

Reflex logo component for branding and attribution.

767

768

Args:

769

**props: Logo styling and sizing options

770

771

Returns:

772

Reflex logo component

773

"""

774

...

775

```

776

777

## Usage Examples

778

779

### Complete File Upload System

780

781

```python

782

class FileManagerState(rx.State):

783

files: list[dict] = []

784

upload_progress: dict = {}

785

786

async def handle_upload(self, files: list[rx.UploadFile]):

787

for file in files:

788

# Validate file

789

if not self.validate_file(file):

790

continue

791

792

# Process file

793

processed_file = {

794

"name": file.filename,

795

"size": file.size,

796

"type": file.content_type,

797

"url": rx.get_upload_url(file.filename),

798

"uploaded_at": datetime.now()

799

}

800

801

self.files.append(processed_file)

802

803

def validate_file(self, file: rx.UploadFile) -> bool:

804

# Size validation (10MB limit)

805

if file.size > 10 * 1024 * 1024:

806

return False

807

808

# Type validation

809

allowed_types = ["image/jpeg", "image/png", "application/pdf"]

810

return file.content_type in allowed_types

811

812

def file_manager():

813

return rx.vstack(

814

rx.upload(

815

rx.card(

816

rx.vstack(

817

rx.icon("upload"),

818

rx.text("Drop files here or click to upload"),

819

rx.text("Max 10MB per file", size="sm", color="gray"),

820

align="center",

821

spacing="2"

822

),

823

variant="surface"

824

),

825

multiple=True,

826

accept=[".jpg", ".png", ".pdf"],

827

on_upload=FileManagerState.handle_upload

828

),

829

rx.foreach(

830

FileManagerState.files,

831

lambda file: rx.card(

832

rx.hstack(

833

rx.text(file["name"]),

834

rx.spacer(),

835

rx.text(f"{file['size']} bytes", size="sm"),

836

align="center"

837

)

838

)

839

)

840

)

841

```

842

843

### Testing Complete Application

844

845

```python

846

import pytest

847

import reflex as rx

848

849

@pytest.fixture

850

def app():

851

return rx.App()

852

853

@pytest.fixture

854

def client(app):

855

return rx.testing.TestClient(app)

856

857

def test_user_registration(client):

858

# Test user registration flow

859

response = client.post("/api/register", data={

860

"username": "testuser",

861

"email": "test@example.com",

862

"password": "secure123"

863

})

864

865

assert response.status_code == 201

866

assert response.json()["username"] == "testuser"

867

868

def test_state_persistence():

869

# Test state management

870

state = rx.testing.StateTester.create_state(UserState)

871

872

# Test login

873

changes = rx.testing.StateTester.trigger_event(

874

state, "login", "testuser", "secure123"

875

)

876

assert changes["is_logged_in"] == True

877

assert changes["username"] == "testuser"

878

```

879

880

## Types

881

882

```python { .api }

883

from typing import Any, Dict, List, Optional, Union, BinaryIO, Callable

884

from datetime import datetime

885

886

# File Upload Types

887

FileContent = BinaryIO # File content stream

888

FileMetadata = Dict[str, Any] # File metadata dictionary

889

UploadConfig = Dict[str, Any] # Upload configuration

890

891

# Middleware Types

892

MiddlewareFunc = Callable[[Any], Any] # Middleware function

893

RequestHandler = Callable # Request handler function

894

ResponseHandler = Callable # Response handler function

895

896

# Testing Types

897

TestResponse = Any # HTTP test response

898

ComponentRender = Dict[str, Any] # Rendered component representation

899

StateChanges = Dict[str, Any] # State change dictionary

900

901

# Admin Types

902

ModelConfig = Dict[str, Any] # Admin model configuration

903

AdminView = Callable[[], Component] # Admin view function

904

PermissionRule = Dict[str, Any] # Permission configuration

905

906

# Chart Types

907

PlotlyFigure = Dict[str, Any] # Plotly figure dictionary

908

ChartData = List[Dict[str, Any]] # Chart data as list of records

909

TableColumn = Dict[str, Any] # Table column configuration

910

911

# Notification Types

912

ToastVariant = Literal["info", "success", "warning", "error"]

913

ToastPosition = Literal["top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right"]

914

915

# Content Types

916

MarkdownContent = str # Markdown content string

917

CodeContent = str # Source code content

918

LanguageIdentifier = str # Programming language name

919

```