or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-server.mdcolors-transforms.mdcommand-line.mddocument-management.mdembedding-integration.mdevents-interactivity.mdindex.mdio-operations.mdlayouts.mdmodels-data-sources.mdplotting-interface.mdserver-applications.mdwidgets.md

document-management.mddocs/

0

# Document Management

1

2

Document model and lifecycle management for Bokeh applications. The Document serves as the central container for all Bokeh models, managing their relationships, state changes, and synchronization between client and server in interactive applications.

3

4

## Capabilities

5

6

### Document Core

7

8

The main Document class that serves as the container for all Bokeh models and manages their state.

9

10

```python { .api }

11

class Document:

12

"""

13

Central container for all Bokeh models in an application.

14

15

The Document manages model relationships, handles state changes,

16

coordinates updates between client and server, and provides

17

the foundation for interactive Bokeh applications.

18

"""

19

def __init__(self, **kwargs):

20

"""

21

Parameters:

22

- title: str, document title (default: "Bokeh Application")

23

"""

24

25

def add_root(self, model):

26

"""

27

Add a model as a root element to the document.

28

29

Parameters:

30

- model: Model, Bokeh model to add as root

31

"""

32

33

def remove_root(self, model):

34

"""

35

Remove a root model from the document.

36

37

Parameters:

38

- model: Model, root model to remove

39

"""

40

41

@property

42

def roots(self):

43

"""List of root models in the document."""

44

45

@property

46

def title(self):

47

"""Document title string."""

48

49

@title.setter

50

def title(self, value):

51

"""Set document title."""

52

53

def clear(self):

54

"""Remove all models from the document."""

55

56

def add_periodic_callback(self, callback, period_milliseconds):

57

"""

58

Add a periodic callback function.

59

60

Parameters:

61

- callback: callable, function to call periodically

62

- period_milliseconds: int, callback interval in milliseconds

63

64

Returns:

65

Callback handle for later removal

66

"""

67

68

def remove_periodic_callback(self, callback_handle):

69

"""

70

Remove a periodic callback.

71

72

Parameters:

73

- callback_handle: handle returned by add_periodic_callback

74

"""

75

76

def add_timeout_callback(self, callback, timeout_milliseconds):

77

"""

78

Add a one-time timeout callback.

79

80

Parameters:

81

- callback: callable, function to call after timeout

82

- timeout_milliseconds: int, timeout in milliseconds

83

84

Returns:

85

Callback handle for cancellation

86

"""

87

88

def remove_timeout_callback(self, callback_handle):

89

"""

90

Remove a timeout callback before it executes.

91

92

Parameters:

93

- callback_handle: handle returned by add_timeout_callback

94

"""

95

96

DEFAULT_TITLE: str # "Bokeh Application"

97

```

98

99

### Document Context Management

100

101

Functions and utilities for managing document context in different environments.

102

103

```python { .api }

104

def curdoc():

105

"""

106

Get the current Document instance.

107

108

Returns the Document associated with the current context:

109

- In server applications: the session document

110

- In standalone scripts: a default document

111

- In notebooks: the notebook document

112

113

Returns:

114

Document: Current document instance

115

"""

116

117

def without_document_lock(func):

118

"""

119

Decorator to execute function without document lock.

120

121

Used when modifying documents from background threads

122

or async operations in server applications.

123

124

Parameters:

125

- func: callable, function to execute without lock

126

127

Returns:

128

Decorated function that executes without document lock

129

"""

130

131

def set_curdoc(doc):

132

"""

133

Set the current document for the execution context.

134

135

Parameters:

136

- doc: Document, document to set as current

137

"""

138

```

139

140

### Model Management

141

142

Functions for managing models within documents and handling model relationships.

143

144

```python { .api }

145

class Model:

146

"""Base class for all Bokeh models."""

147

148

@property

149

def document(self):

150

"""Get the document containing this model."""

151

152

def select(self, selector):

153

"""

154

Find models matching the given selector.

155

156

Parameters:

157

- selector: dict or type, selection criteria

158

159

Returns:

160

List of matching models

161

"""

162

163

def select_one(self, selector):

164

"""

165

Find the first model matching the given selector.

166

167

Parameters:

168

- selector: dict or type, selection criteria

169

170

Returns:

171

First matching model or None

172

"""

173

174

def collect_models(*models):

175

"""

176

Collect all models in a object graph.

177

178

Parameters:

179

- models: Model objects to traverse

180

181

Returns:

182

Set of all models found in the graph

183

"""

184

```

185

186

### Document Events and Callbacks

187

188

Event system for responding to document and model changes.

189

190

```python { .api }

191

class DocumentChangedEvent:

192

"""Base class for document change events."""

193

194

def __init__(self, document, **kwargs):

195

"""

196

Parameters:

197

- document: Document, document that changed

198

"""

199

200

class ModelChangedEvent(DocumentChangedEvent):

201

"""Event fired when a model property changes."""

202

203

def __init__(self, document, model, attr, old, new, **kwargs):

204

"""

205

Parameters:

206

- document: Document, containing document

207

- model: Model, model that changed

208

- attr: str, property name that changed

209

- old: any, previous property value

210

- new: any, new property value

211

"""

212

213

class RootAddedEvent(DocumentChangedEvent):

214

"""Event fired when a root model is added."""

215

216

def __init__(self, document, model, **kwargs):

217

"""

218

Parameters:

219

- document: Document, containing document

220

- model: Model, root model that was added

221

"""

222

223

class RootRemovedEvent(DocumentChangedEvent):

224

"""Event fired when a root model is removed."""

225

226

def __init__(self, document, model, **kwargs):

227

"""

228

Parameters:

229

- document: Document, containing document

230

- model: Model, root model that was removed

231

"""

232

233

class TitleChangedEvent(DocumentChangedEvent):

234

"""Event fired when document title changes."""

235

236

def __init__(self, document, title, **kwargs):

237

"""

238

Parameters:

239

- document: Document, document with changed title

240

- title: str, new document title

241

"""

242

```

243

244

### Document Serialization

245

246

Functions for serializing and deserializing documents for transmission and storage.

247

248

```python { .api }

249

def to_json(obj):

250

"""

251

Serialize a document or model to JSON.

252

253

Parameters:

254

- obj: Document or Model, object to serialize

255

256

Returns:

257

str: JSON representation

258

"""

259

260

def from_json(json_str):

261

"""

262

Deserialize a document or model from JSON.

263

264

Parameters:

265

- json_str: str, JSON representation

266

267

Returns:

268

Document or Model: Deserialized object

269

"""

270

271

def to_json_string(obj, **kwargs):

272

"""

273

Serialize object to JSON string with formatting options.

274

275

Parameters:

276

- obj: object to serialize

277

- indent: int, JSON indentation

278

- sort_keys: bool, sort object keys

279

280

Returns:

281

str: Formatted JSON string

282

"""

283

```

284

285

### Document Validation

286

287

Functions for validating document structure and model consistency.

288

289

```python { .api }

290

def validate_document(doc):

291

"""

292

Validate document structure and model consistency.

293

294

Parameters:

295

- doc: Document, document to validate

296

297

Returns:

298

List of validation issues found

299

"""

300

301

class ValidationError(Exception):

302

"""Exception raised for document validation errors."""

303

304

def __init__(self, message, models=None, **kwargs):

305

"""

306

Parameters:

307

- message: str, error description

308

- models: list, models involved in the error

309

"""

310

```

311

312

### Document Templates

313

314

Utilities for creating document templates and reusable document patterns.

315

316

```python { .api }

317

class DocumentTemplate:

318

"""Template for creating documents with predefined structure."""

319

320

def __init__(self, **kwargs):

321

"""

322

Parameters:

323

- template_vars: dict, template variables

324

"""

325

326

def create_document(self, **vars):

327

"""

328

Create a document from the template.

329

330

Parameters:

331

- vars: template variable values

332

333

Returns:

334

Document: Created document instance

335

"""

336

337

def create_document_from_template(template_path, **vars):

338

"""

339

Create document from template file.

340

341

Parameters:

342

- template_path: str, path to template file

343

- vars: template variable values

344

345

Returns:

346

Document: Created document

347

"""

348

```

349

350

## Usage Examples

351

352

### Basic Document Management

353

354

```python

355

from bokeh.document import Document

356

from bokeh.plotting import figure

357

from bokeh.models.widgets import Button

358

from bokeh.layouts import column

359

360

# Create a new document

361

doc = Document(title="My Application")

362

363

# Create models

364

plot = figure(width=400, height=400)

365

plot.circle([1, 2, 3], [4, 5, 6], size=10)

366

367

button = Button(label="Click me")

368

369

# Add models to document

370

layout = column(button, plot)

371

doc.add_root(layout)

372

373

print(f"Document has {len(doc.roots)} root models")

374

print(f"Document title: {doc.title}")

375

```

376

377

### Document with Callbacks

378

379

```python

380

from bokeh.io import curdoc

381

from bokeh.plotting import figure

382

from bokeh.models import ColumnDataSource

383

import numpy as np

384

385

# Get current document

386

doc = curdoc()

387

388

# Create data source and plot

389

source = ColumnDataSource(data=dict(x=[1, 2, 3], y=[4, 5, 6]))

390

plot = figure()

391

plot.circle('x', 'y', source=source, size=10)

392

393

def update_data():

394

# Update data periodically

395

new_data = dict(

396

x=np.random.random(5),

397

y=np.random.random(5)

398

)

399

source.data = new_data

400

401

# Add periodic callback

402

callback_handle = doc.add_periodic_callback(update_data, 1000)

403

404

# Add plot to document

405

doc.add_root(plot)

406

407

# Later, remove callback if needed

408

# doc.remove_periodic_callback(callback_handle)

409

```

410

411

### Document Event Handling

412

413

```python

414

from bokeh.document import Document

415

from bokeh.plotting import figure

416

from bokeh.models.widgets import Slider

417

418

# Create document

419

doc = Document()

420

421

# Create models

422

plot = figure()

423

slider = Slider(title="Value", start=0, end=100, value=50)

424

425

def on_document_change(event):

426

print(f"Document changed: {type(event).__name__}")

427

if hasattr(event, 'model'):

428

print(f"Model: {event.model}")

429

if hasattr(event, 'attr'):

430

print(f"Attribute: {event.attr}, New value: {event.new}")

431

432

# Listen for document changes

433

doc.on_change(on_document_change)

434

435

# Add models (will trigger events)

436

doc.add_root(plot)

437

doc.add_root(slider)

438

439

# Change slider value (will trigger event)

440

slider.value = 75

441

```

442

443

### Document Validation

444

445

```python

446

from bokeh.document import Document, validate_document

447

from bokeh.plotting import figure

448

from bokeh.models import ColumnDataSource

449

450

# Create document with potential issues

451

doc = Document()

452

453

# Create plot with invalid data source reference

454

plot = figure()

455

# Intentionally reference non-existent data source

456

plot.circle('x', 'y', source="invalid_source")

457

458

doc.add_root(plot)

459

460

# Validate document

461

issues = validate_document(doc)

462

if issues:

463

print("Validation issues found:")

464

for issue in issues:

465

print(f"- {issue}")

466

else:

467

print("Document is valid")

468

```

469

470

### Multiple Document Management

471

472

```python

473

from bokeh.document import Document, set_curdoc, curdoc

474

from bokeh.plotting import figure

475

476

# Create multiple documents

477

doc1 = Document(title="Document 1")

478

doc2 = Document(title="Document 2")

479

480

# Work with first document

481

set_curdoc(doc1)

482

plot1 = figure(title="Plot 1")

483

plot1.line([1, 2, 3], [1, 4, 2])

484

curdoc().add_root(plot1)

485

486

# Switch to second document

487

set_curdoc(doc2)

488

plot2 = figure(title="Plot 2")

489

plot2.circle([1, 2, 3], [3, 1, 4], size=10)

490

curdoc().add_root(plot2)

491

492

print(f"Doc 1 title: {doc1.title}, roots: {len(doc1.roots)}")

493

print(f"Doc 2 title: {doc2.title}, roots: {len(doc2.roots)}")

494

```

495

496

## Common Data Types

497

498

```python { .api }

499

# Document-related types

500

DocumentLike = Union[Document, None]

501

ModelLike = Union[Model, str]

502

CallbackLike = Callable[[], None]

503

EventLike = Union[DocumentChangedEvent, ModelChangedEvent]

504

505

# Callback types

506

PeriodicCallbackHandle = Any # Handle for periodic callbacks

507

TimeoutCallbackHandle = Any # Handle for timeout callbacks

508

PeriodType = int # Milliseconds for callback periods

509

510

# Validation types

511

ValidationIssue = str # Validation error description

512

ValidationResult = List[ValidationIssue]

513

514

# Serialization types

515

JSONDict = Dict[str, Any] # JSON object representation

516

JSONString = str # JSON string representation

517

```