or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application.mdasync-io.mdauth.mddistributed.mddns.mdemail.mdhttp.mdindex.mdlogging.mdprotocols.mdssh.mdtesting.md

application.mddocs/

0

# Application Framework

1

2

Service-oriented application architecture with hierarchical service management, plugin system, and daemon utilities for building long-running applications. Twisted's application framework provides structure for complex server applications.

3

4

## Capabilities

5

6

### Service Interface and Implementations

7

8

Core service abstractions and implementations for building modular applications.

9

10

```python { .api }

11

class service.IService:

12

"""

13

Interface for services that can be started and stopped.

14

15

Services form the building blocks of Twisted applications.

16

"""

17

def startService():

18

"""Start the service."""

19

20

def stopService():

21

"""

22

Stop the service.

23

24

Returns:

25

None or Deferred: Completion indicator

26

"""

27

28

def privilegedStartService():

29

"""Start service with privileges (before dropping root)."""

30

31

class service.Service:

32

"""

33

Base implementation of IService.

34

35

Attributes:

36

- name: Service name (str)

37

- parent: Parent service container

38

- running: Whether service is running (bool)

39

"""

40

name = None

41

parent = None

42

running = False

43

44

def __init__(self):

45

"""Initialize service."""

46

47

def startService(self):

48

"""

49

Start the service.

50

Sets running=True and calls child services' startService.

51

"""

52

53

def stopService(self):

54

"""

55

Stop the service.

56

57

Returns:

58

Deferred: Fires when service and all children are stopped

59

"""

60

61

def privilegedStartService(self):

62

"""Start service with elevated privileges."""

63

64

def setName(self, name):

65

"""

66

Set service name.

67

68

Args:

69

name (str): Service name

70

"""

71

72

def setServiceParent(self, parent):

73

"""

74

Set parent service container.

75

76

Args:

77

parent: Parent service (IServiceCollection)

78

"""

79

80

def disownServiceParent(self):

81

"""Remove this service from its parent."""

82

83

class service.MultiService:

84

"""

85

Service container that manages multiple child services.

86

87

Attributes:

88

- services: List of child services

89

- namedServices: Dict of named child services

90

"""

91

services = None

92

namedServices = None

93

94

def __init__(self):

95

"""Initialize multi-service container."""

96

97

def addService(self, service):

98

"""

99

Add a child service.

100

101

Args:

102

service: Service to add (IService)

103

"""

104

105

def removeService(self, service):

106

"""

107

Remove a child service.

108

109

Args:

110

service: Service to remove

111

"""

112

113

def getServiceNamed(self, name):

114

"""

115

Get child service by name.

116

117

Args:

118

name (str): Service name

119

120

Returns:

121

Service: Named service or None

122

"""

123

124

def privilegeStart(self):

125

"""Start all child services with privileges."""

126

127

def startService(self):

128

"""Start this service and all children."""

129

130

def stopService(self):

131

"""

132

Stop this service and all children.

133

134

Returns:

135

Deferred: Fires when all services stopped

136

"""

137

138

class service.Application:

139

"""

140

Top-level application container.

141

142

Attributes:

143

- name: Application name

144

- uid: User ID to run as (int)

145

- gid: Group ID to run as (int)

146

"""

147

name = None

148

uid = None

149

gid = None

150

151

def __init__(self, name, uid=None, gid=None):

152

"""

153

Args:

154

name (str): Application name

155

uid (int): User ID to switch to

156

gid (int): Group ID to switch to

157

"""

158

159

def setComponent(self, interface, component):

160

"""

161

Register component for interface.

162

163

Args:

164

interface: Component interface

165

component: Component implementation

166

"""

167

168

def getComponent(self, interface, default=None):

169

"""

170

Get component for interface.

171

172

Args:

173

interface: Component interface

174

default: Default if not found

175

176

Returns:

177

Component or default

178

"""

179

```

180

181

**Service Usage Example**:

182

183

```python

184

from twisted.application import service

185

from twisted.internet import reactor, endpoints

186

from twisted.web import server, resource

187

188

class WebService(service.Service):

189

"""Custom web service."""

190

191

def __init__(self, port, resource):

192

service.Service.__init__(self)

193

self.port = port

194

self.resource = resource

195

self.site = None

196

self.listening_port = None

197

198

def startService(self):

199

service.Service.startService(self)

200

self.site = server.Site(self.resource)

201

endpoint = endpoints.TCP4ServerEndpoint(reactor, self.port)

202

self.listening_port = endpoint.listen(self.site)

203

print(f"Web service started on port {self.port}")

204

205

def stopService(self):

206

if self.listening_port:

207

d = self.listening_port.stopListening()

208

print("Web service stopped")

209

return d

210

return service.Service.stopService(self)

211

212

# Create application with multiple services

213

application = service.Application("MyApp")

214

215

# Create multi-service container

216

main_service = service.MultiService()

217

main_service.setServiceParent(application)

218

219

# Add web service

220

web_resource = resource.Resource()

221

web_service = WebService(8080, web_resource)

222

web_service.setName("web")

223

web_service.setServiceParent(main_service)

224

225

# Add another service

226

other_service = service.Service()

227

other_service.setName("other")

228

other_service.setServiceParent(main_service)

229

```

230

231

### Internet Services

232

233

Pre-built service implementations for common network operations.

234

235

```python { .api }

236

class internet.TCPServer:

237

"""

238

TCP server service.

239

"""

240

def __init__(self, port, factory, backlog=50, interface=''):

241

"""

242

Args:

243

port (int): Port to listen on

244

factory: Protocol factory

245

backlog (int): Listen backlog size

246

interface (str): Interface to bind to

247

"""

248

249

class internet.TCPClient:

250

"""

251

TCP client service that maintains persistent connection.

252

"""

253

def __init__(self, host, port, factory):

254

"""

255

Args:

256

host (str): Server hostname

257

port (int): Server port

258

factory: Client factory

259

"""

260

261

class internet.UDPServer:

262

"""

263

UDP server service.

264

"""

265

def __init__(self, port, protocol, interface='', maxPacketSize=8192):

266

"""

267

Args:

268

port (int): Port to bind to

269

protocol: UDP protocol instance

270

interface (str): Interface to bind to

271

maxPacketSize (int): Maximum packet size

272

"""

273

274

class internet.SSLServer:

275

"""

276

SSL server service.

277

"""

278

def __init__(self, port, factory, contextFactory, backlog=50, interface=''):

279

"""

280

Args:

281

port (int): Port to listen on

282

factory: Protocol factory

283

contextFactory: SSL context factory

284

backlog (int): Listen backlog

285

interface (str): Interface to bind to

286

"""

287

288

class internet.SSLClient:

289

"""

290

SSL client service.

291

"""

292

def __init__(self, host, port, factory, contextFactory):

293

"""

294

Args:

295

host (str): Server hostname

296

port (int): Server port

297

factory: Client factory

298

contextFactory: SSL context factory

299

"""

300

301

class internet.UNIXServer:

302

"""

303

Unix domain socket server service.

304

"""

305

def __init__(self, address, factory, backlog=50, mode=0o666, wantPID=0):

306

"""

307

Args:

308

address (str): Socket file path

309

factory: Protocol factory

310

backlog (int): Listen backlog

311

mode (int): Socket file permissions

312

wantPID (bool): Include PID in address

313

"""

314

315

class internet.TimerService:

316

"""

317

Service that calls a function periodically.

318

"""

319

def __init__(self, step, callable, *args, **kwargs):

320

"""

321

Args:

322

step (float): Interval between calls in seconds

323

callable: Function to call

324

*args, **kwargs: Arguments for function

325

"""

326

327

def startService(self):

328

"""Start the timer service."""

329

330

def stopService(self):

331

"""

332

Stop the timer service.

333

334

Returns:

335

Deferred: Fires when stopped

336

"""

337

```

338

339

**Internet Services Usage Example**:

340

341

```python

342

from twisted.application import service, internet

343

from twisted.internet import protocol

344

from twisted.web import server, resource

345

346

# Create application

347

application = service.Application("ServerApp")

348

349

# TCP server service

350

class EchoProtocol(protocol.Protocol):

351

def dataReceived(self, data):

352

self.transport.write(data)

353

354

echo_factory = protocol.ServerFactory()

355

echo_factory.protocol = EchoProtocol

356

357

tcp_service = internet.TCPServer(8080, echo_factory)

358

tcp_service.setServiceParent(application)

359

360

# Timer service for periodic tasks

361

def heartbeat():

362

print("Heartbeat...")

363

364

timer_service = internet.TimerService(30.0, heartbeat)

365

timer_service.setServiceParent(application)

366

367

# Web server service

368

root = resource.Resource()

369

site = server.Site(root)

370

web_service = internet.TCPServer(8000, site)

371

web_service.setServiceParent(application)

372

```

373

374

### String Port Specifications

375

376

String-based configuration for network services.

377

378

```python { .api }

379

def strports.parse(description, factory, *args, **kw):

380

"""

381

Parse port specification string and create listening port.

382

383

Args:

384

description (str): Port specification (e.g., "tcp:8080")

385

factory: Protocol factory

386

*args, **kw: Additional arguments

387

388

Returns:

389

Port: Listening port object

390

"""

391

392

def strports.listen(description, factory):

393

"""

394

Listen on port specified by string description.

395

396

Args:

397

description (str): Port specification

398

factory: Protocol factory

399

400

Returns:

401

Port: Listening port object

402

"""

403

404

def strports.service(description, factory, *args, **kw):

405

"""

406

Create service from port specification string.

407

408

Args:

409

description (str): Port specification

410

factory: Protocol factory

411

*args, **kw: Additional arguments

412

413

Returns:

414

Service: Service object

415

"""

416

```

417

418

**String Port Examples**:

419

420

```

421

tcp:8080 # TCP port 8080, all interfaces

422

tcp:8080:interface=127.0.0.1 # TCP port 8080, localhost only

423

ssl:8443 # SSL port 8443

424

unix:/tmp/socket # Unix domain socket

425

systemd:domain=INET # systemd socket activation

426

```

427

428

### Application Loading and Running

429

430

Functions for loading and running Twisted applications.

431

432

```python { .api }

433

def app.run(runApp, ServerOptions):

434

"""

435

Run a Twisted application.

436

437

Args:

438

runApp: Application callable

439

ServerOptions: Server configuration options

440

"""

441

442

def app.startApplication(application, save):

443

"""

444

Start a Twisted application.

445

446

Args:

447

application: Application object

448

save (bool): Whether to save application state

449

"""

450

451

def app.getApplication(config, passphrase):

452

"""

453

Load application from configuration.

454

455

Args:

456

config: Configuration object

457

passphrase: Decryption passphrase

458

459

Returns:

460

Application: Loaded application

461

"""

462

463

class app.ServerOptions:

464

"""

465

Command-line options for server applications.

466

467

Attributes:

468

- profile: Enable profiling

469

- profiler: Profiler module to use

470

- debug: Enable debug mode

471

- logfile: Log file path

472

- pidfile: PID file path

473

- chroot: Chroot directory

474

- uid: User ID to switch to

475

- gid: Group ID to switch to

476

"""

477

profile = False

478

profiler = 'hotshot'

479

debug = False

480

logfile = None

481

pidfile = None

482

chroot = None

483

uid = None

484

gid = None

485

```

486

487

### Reactor Selection

488

489

Utilities for selecting and installing reactors.

490

491

```python { .api }

492

def reactors.installReactor(shortName):

493

"""

494

Install named reactor.

495

496

Args:

497

shortName (str): Reactor name ('select', 'epoll', 'kqueue', etc.)

498

499

Returns:

500

Reactor: Installed reactor instance

501

"""

502

503

def reactors.getReactorTypes():

504

"""

505

Get available reactor types.

506

507

Returns:

508

dict: Mapping of names to reactor descriptions

509

"""

510

511

def reactors.default():

512

"""

513

Get default reactor for current platform.

514

515

Returns:

516

Reactor: Default reactor

517

"""

518

```

519

520

**Reactor Selection Example**:

521

522

```python

523

from twisted.application import reactors

524

525

# Get available reactors

526

reactor_types = reactors.getReactorTypes()

527

print("Available reactors:", list(reactor_types.keys()))

528

529

# Install specific reactor

530

try:

531

reactor = reactors.installReactor('epoll')

532

print("Installed epoll reactor")

533

except ImportError:

534

reactor = reactors.installReactor('select')

535

print("Fallback to select reactor")

536

```

537

538

### Plugin System

539

540

Plugin discovery and loading infrastructure.

541

542

```python { .api }

543

class service.IServiceMaker:

544

"""

545

Interface for service maker plugins.

546

547

Plugins implementing this interface can create services

548

from command-line options.

549

"""

550

tapname = None # Plugin name

551

description = None # Plugin description

552

options = None # Options class

553

554

def makeService(options):

555

"""

556

Create service from options.

557

558

Args:

559

options: Parsed command-line options

560

561

Returns:

562

Service: Created service

563

"""

564

565

# Plugin registration uses Twisted's plugin system

566

# Plugins are discovered in twisted/plugins/ directories

567

```

568

569

**Plugin Example**:

570

571

```python

572

# In myapp/plugins/myservice_plugin.py

573

from twisted.application.service import IServiceMaker

574

from twisted.plugin import IPlugin

575

from twisted.python import usage

576

from zope.interface import implementer

577

578

class Options(usage.Options):

579

optParameters = [

580

['port', 'p', 8080, 'Port to listen on'],

581

['interface', 'i', '127.0.0.1', 'Interface to bind to'],

582

]

583

584

@implementer(IServiceMaker, IPlugin)

585

class MyServiceMaker:

586

tapname = "myservice"

587

description = "My custom service"

588

options = Options

589

590

def makeService(self, options):

591

from myapp.service import MyService

592

return MyService(options['port'], options['interface'])

593

594

# Register the plugin

595

serviceMaker = MyServiceMaker()

596

```

597

598

### TAC Files (Twisted Application Configuration)

599

600

Configuration files for Twisted applications.

601

602

```python

603

# Example .tac file: application.tac

604

605

from twisted.application import service, internet

606

from twisted.web import server, resource, static

607

from twisted.python import log

608

609

# Create the application

610

application = service.Application("WebServer")

611

612

# Create a web resource

613

root = static.File("/var/www")

614

site = server.Site(root)

615

616

# Create and configure services

617

web_service = internet.TCPServer(8080, site)

618

web_service.setServiceParent(application)

619

620

# Optional: Set up logging

621

log.msg("Web server application configured")

622

```

623

624

**Running TAC files**:

625

626

```bash

627

# Run with twistd

628

twistd -y application.tac

629

630

# Run in foreground with logging

631

twistd -n -y application.tac

632

633

# Run as daemon with specific reactor

634

twistd -r epoll -y application.tac

635

```