or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

blueprints.mdconfiguration.mdcore-application.mdexceptions.mdindex.mdmiddleware-signals.mdrequest-response.mdserver-deployment.mdwebsockets.md

core-application.mddocs/

0

# Core Application

1

2

The Sanic application class serves as the main entry point for creating web applications. It provides routing, middleware management, server lifecycle control, and all core functionality needed to build high-performance web services.

3

4

## Capabilities

5

6

### Application Initialization

7

8

Create a new Sanic application instance with customizable configuration and behavior options.

9

10

```python { .api }

11

class Sanic:

12

def __init__(

13

self,

14

name: str,

15

config: Optional[Config] = None,

16

ctx: Optional[Any] = None,

17

router: Optional[Router] = None,

18

signal_router: Optional[SignalRouter] = None,

19

error_handler: Optional[ErrorHandler] = None,

20

env_prefix: Optional[str] = "SANIC_",

21

request_class: Optional[type[Request]] = None,

22

strict_slashes: bool = False,

23

log_config: Optional[dict[str, Any]] = None,

24

configure_logging: bool = True,

25

dumps: Optional[Callable[..., AnyStr]] = None,

26

loads: Optional[Callable[..., Any]] = None,

27

inspector: bool = False,

28

inspector_class: Optional[type[Inspector]] = None,

29

certloader_class: Optional[type[CertLoader]] = None,

30

):

31

"""

32

Initialize a Sanic application.

33

34

Parameters:

35

- name: Application name (used for logging and identification)

36

- config: Custom configuration instance

37

- ctx: Application context object

38

- router: Custom router instance

39

- signal_router: Custom signal router instance

40

- error_handler: Custom error handler instance

41

- env_prefix: Prefix for environment variables (default: "SANIC_")

42

- request_class: Custom request class

43

- strict_slashes: Enforce strict slash handling

44

- log_config: Logging configuration dictionary

45

- configure_logging: Whether to configure logging automatically

46

- dumps: JSON serialization function

47

- loads: JSON deserialization function

48

- inspector: Enable application inspector

49

- inspector_class: Custom inspector class

50

- certloader_class: Custom certificate loader class

51

"""

52

```

53

54

### HTTP Route Decorators

55

56

Define HTTP endpoints using method-specific decorators for clean, readable route definitions.

57

58

```python { .api }

59

def route(

60

self,

61

uri: str,

62

methods: list = None,

63

host: str = None,

64

strict_slashes: bool = None,

65

stream: bool = False,

66

version: int = None,

67

name: str = None,

68

ignore_body: bool = False,

69

apply: list = None,

70

subprotocols: list = None,

71

websocket: bool = False,

72

unquote: bool = False,

73

static: bool = False,

74

version_prefix: str = "/v",

75

error_format: str = None,

76

ctx: Any = None,

77

):

78

"""

79

Decorator for defining HTTP routes.

80

81

Parameters:

82

- uri: Route path with optional parameters

83

- methods: HTTP methods (defaults to ['GET'])

84

- host: Host restriction pattern

85

- strict_slashes: Override global strict slash setting

86

- stream: Enable request streaming

87

- version: API version number

88

- name: Route name for url_for

89

- ignore_body: Don't parse request body

90

- apply: List of decorators to apply

91

- subprotocols: WebSocket subprotocols

92

- websocket: Mark as WebSocket route

93

- unquote: URL decode path parameters

94

- static: Mark as static file route

95

- version_prefix: Version URL prefix

96

- error_format: Error response format

97

- ctx: Route-specific context

98

"""

99

100

def get(self, uri: str, **kwargs):

101

"""GET method decorator."""

102

103

def post(self, uri: str, **kwargs):

104

"""POST method decorator."""

105

106

def put(self, uri: str, **kwargs):

107

"""PUT method decorator."""

108

109

def delete(self, uri: str, **kwargs):

110

"""DELETE method decorator."""

111

112

def patch(self, uri: str, **kwargs):

113

"""PATCH method decorator."""

114

115

def head(self, uri: str, **kwargs):

116

"""HEAD method decorator."""

117

118

def options(self, uri: str, **kwargs):

119

"""OPTIONS method decorator."""

120

```

121

122

### Programmatic Routing

123

124

Add routes programmatically without decorators for dynamic route creation and advanced routing scenarios.

125

126

```python { .api }

127

def add_route(

128

self,

129

handler,

130

uri: str,

131

methods: list = None,

132

**kwargs

133

):

134

"""

135

Add a route programmatically.

136

137

Parameters:

138

- handler: Handler function

139

- uri: Route path

140

- methods: HTTP methods list

141

- **kwargs: Additional route options

142

"""

143

144

def add_websocket_route(

145

self,

146

handler,

147

uri: str,

148

**kwargs

149

):

150

"""

151

Add a WebSocket route programmatically.

152

153

Parameters:

154

- handler: WebSocket handler function

155

- uri: WebSocket path

156

- **kwargs: Additional route options

157

"""

158

```

159

160

### Static File Serving

161

162

Serve static files and directories with customizable options for caching, security, and performance.

163

164

```python { .api }

165

def static(

166

self,

167

uri: str,

168

file_or_directory: str,

169

pattern: str = r"/?.+",

170

use_modified_since: bool = True,

171

use_content_range: bool = False,

172

stream_large_files: bool = False,

173

name: str = "static",

174

host: str = None,

175

strict_slashes: bool = None,

176

content_type: str = None,

177

apply: list = None,

178

resource_type: str = "file",

179

index: str = None,

180

directory_view: bool = False,

181

directory_handler: Callable = None,

182

):

183

"""

184

Serve static files or directories.

185

186

Parameters:

187

- uri: URL path for static files

188

- file_or_directory: Path to file or directory

189

- pattern: File matching pattern

190

- use_modified_since: Enable conditional requests

191

- use_content_range: Enable range requests

192

- stream_large_files: Stream large files

193

- name: Route name

194

- host: Host restriction

195

- strict_slashes: Slash handling

196

- content_type: Override content type

197

- apply: Decorators to apply

198

- resource_type: Resource type identifier

199

- index: Directory index file

200

- directory_view: Enable directory listing

201

- directory_handler: Custom directory handler

202

"""

203

```

204

205

### WebSocket Routes

206

207

Define WebSocket endpoints for real-time bidirectional communication.

208

209

```python { .api }

210

def websocket(

211

self,

212

uri: str,

213

host: str = None,

214

strict_slashes: bool = None,

215

subprotocols: list = None,

216

name: str = None,

217

apply: list = None,

218

version: int = None,

219

version_prefix: str = "/v",

220

error_format: str = None,

221

):

222

"""

223

Decorator for WebSocket routes.

224

225

Parameters:

226

- uri: WebSocket path

227

- host: Host restriction

228

- strict_slashes: Slash handling

229

- subprotocols: Supported subprotocols

230

- name: Route name

231

- apply: Decorators to apply

232

- version: API version

233

- version_prefix: Version prefix

234

- error_format: Error format

235

"""

236

```

237

238

### Server Lifecycle

239

240

Control server startup, shutdown, and runtime behavior with comprehensive configuration options.

241

242

```python { .api }

243

def run(

244

self,

245

host: str = "127.0.0.1",

246

port: int = 8000,

247

debug: bool = False,

248

ssl: dict = None,

249

sock: socket = None,

250

workers: int = 1,

251

protocol: Type = None,

252

backlog: int = 100,

253

stop_event: Event = None,

254

register_sys_signals: bool = True,

255

run_multiple: bool = False,

256

run_async: bool = False,

257

connections: set = None,

258

signal: Signal = None,

259

state: dict = None,

260

asyncio_server_kwargs: dict = None,

261

return_asyncio_server: bool = False,

262

**kwargs

263

):

264

"""

265

Run the Sanic server.

266

267

Parameters:

268

- host: Server host address

269

- port: Server port number

270

- debug: Enable debug mode

271

- ssl: SSL configuration dictionary

272

- sock: Custom socket object

273

- workers: Number of worker processes

274

- protocol: Custom protocol class

275

- backlog: Connection backlog size

276

- stop_event: Stop event for graceful shutdown

277

- register_sys_signals: Register system signals

278

- run_multiple: Run multiple workers

279

- run_async: Run asynchronously

280

- connections: Connection set

281

- signal: Signal object

282

- state: Shared state dictionary

283

- asyncio_server_kwargs: Additional asyncio server arguments

284

- return_asyncio_server: Return server object

285

"""

286

287

def create_server(

288

self,

289

host: str = "127.0.0.1",

290

port: int = 8000,

291

**kwargs

292

):

293

"""

294

Create server instance without running.

295

296

Returns:

297

Server instance

298

"""

299

300

def stop(self):

301

"""Stop the running server."""

302

303

def restart(self, **kwargs):

304

"""Restart the server with new configuration."""

305

```

306

307

### Event Listeners

308

309

Register functions to execute during specific server lifecycle events.

310

311

```python { .api }

312

def listener(self, event: str):

313

"""

314

Decorator for event listeners.

315

316

Parameters:

317

- event: Event name ('before_server_start', 'after_server_start',

318

'before_server_stop', 'after_server_stop')

319

"""

320

321

def before_server_start(self, listener: Callable):

322

"""Register before_server_start listener."""

323

324

def after_server_start(self, listener: Callable):

325

"""Register after_server_start listener."""

326

327

def before_server_stop(self, listener: Callable):

328

"""Register before_server_stop listener."""

329

330

def after_server_stop(self, listener: Callable):

331

"""Register after_server_stop listener."""

332

333

def main_process_start(self, listener: Callable):

334

"""Register main_process_start listener."""

335

336

def main_process_ready(self, listener: Callable):

337

"""Register main_process_ready listener."""

338

339

def main_process_stop(self, listener: Callable):

340

"""Register main_process_stop listener."""

341

342

def reload_process_start(self, listener: Callable):

343

"""Register reload_process_start listener."""

344

345

def reload_process_stop(self, listener: Callable):

346

"""Register reload_process_stop listener."""

347

348

def before_reload_trigger(self, listener: Callable):

349

"""Register before_reload_trigger listener."""

350

351

def after_reload_trigger(self, listener: Callable):

352

"""Register after_reload_trigger listener."""

353

```

354

355

### URL Generation and Testing

356

357

Generate URLs for named routes and create test clients for application testing.

358

359

```python { .api }

360

def url_for(

361

self,

362

view_name: str,

363

**kwargs

364

):

365

"""

366

Generate URL for named route.

367

368

Parameters:

369

- view_name: Route name

370

- **kwargs: Route parameters

371

372

Returns:

373

Generated URL string

374

"""

375

376

def test_client(self, **kwargs):

377

"""

378

Create test client for application testing.

379

380

Returns:

381

Test client instance

382

"""

383

384

def asgi_client(self, **kwargs):

385

"""

386

Create ASGI test client.

387

388

Returns:

389

ASGI client instance

390

"""

391

```

392

393

### Middleware Management

394

395

Register middleware functions for request/response processing.

396

397

```python { .api }

398

def middleware(

399

self,

400

middleware_or_request: Union[MiddlewareType, str],

401

attach_to: str = "request",

402

apply: bool = True,

403

*,

404

priority: int = 0,

405

):

406

"""

407

Decorator or method for registering middleware.

408

409

Parameters:

410

- middleware_or_request: Middleware function or attachment point

411

- attach_to: Attach to 'request' or 'response'

412

- apply: Whether to apply the middleware

413

- priority: Middleware priority order

414

"""

415

416

def register_middleware(

417

self,

418

middleware: Union[MiddlewareType, Middleware],

419

attach_to: str = "request",

420

*,

421

priority: Union[Default, int] = _default,

422

):

423

"""

424

Register middleware programmatically.

425

426

Parameters:

427

- middleware: Middleware function or instance

428

- attach_to: Attach to 'request' or 'response'

429

- priority: Middleware priority order

430

"""

431

```

432

433

### Exception Handling

434

435

Register exception handlers for custom error handling.

436

437

```python { .api }

438

def exception(

439

self,

440

*exceptions: Union[type[Exception], Exception],

441

apply: bool = True,

442

):

443

"""

444

Decorator for exception handlers.

445

446

Parameters:

447

- exceptions: Exception types to handle

448

- apply: Whether to apply the handler

449

"""

450

```

451

452

### Signal System

453

454

Register signal handlers for application events.

455

456

```python { .api }

457

def signal(

458

self,

459

event: Union[str, Enum],

460

*,

461

apply: bool = True,

462

condition: Optional[dict[str, Any]] = None,

463

exclusive: bool = True,

464

priority: int = 0,

465

):

466

"""

467

Decorator for signal handlers.

468

469

Parameters:

470

- event: Signal event name

471

- apply: Whether to apply the handler

472

- condition: Signal condition dictionary

473

- exclusive: Whether signal is exclusive

474

- priority: Handler priority

475

"""

476

477

async def dispatch(

478

self,

479

event: str,

480

*,

481

condition: Optional[dict[str, str]] = None,

482

context: Optional[dict[str, Any]] = None,

483

fail_not_found: bool = True,

484

inline: bool = False,

485

reverse: bool = False,

486

):

487

"""

488

Dispatch a signal event.

489

490

Parameters:

491

- event: Event name to dispatch

492

- condition: Event condition

493

- context: Event context data

494

- fail_not_found: Fail if no handlers found

495

- inline: Execute inline

496

- reverse: Execute in reverse order

497

"""

498

```

499

500

### Blueprint Registration

501

502

Register blueprints for modular application organization.

503

504

```python { .api }

505

def blueprint(

506

self,

507

blueprint: Union[Blueprint, Iterable[Blueprint], BlueprintGroup],

508

*,

509

url_prefix: Optional[str] = None,

510

version: Optional[Union[int, float, str]] = None,

511

strict_slashes: Optional[bool] = None,

512

version_prefix: Optional[str] = None,

513

name_prefix: Optional[str] = None,

514

):

515

"""

516

Register one or more blueprints.

517

518

Parameters:

519

- blueprint: Blueprint(s) to register

520

- url_prefix: URL prefix for blueprint routes

521

- version: API version for blueprint

522

- strict_slashes: Strict slash handling

523

- version_prefix: Version prefix format

524

- name_prefix: Name prefix for routes

525

"""

526

```

527

528

### Application Properties

529

530

Access application configuration, context, routing, and other runtime information.

531

532

```python { .api }

533

@property

534

def config(self) -> Config:

535

"""Application configuration object."""

536

537

@property

538

def ctx(self):

539

"""Application context object."""

540

541

@property

542

def router(self):

543

"""Application router instance."""

544

545

@property

546

def blueprints(self) -> dict:

547

"""Registered blueprints dictionary."""

548

549

@property

550

def listeners(self) -> dict:

551

"""Event listeners dictionary."""

552

553

@property

554

def middleware(self) -> list:

555

"""Middleware stack list."""

556

557

@property

558

def request_middleware(self) -> list:

559

"""Request middleware list."""

560

561

@property

562

def response_middleware(self) -> list:

563

"""Response middleware list."""

564

565

@property

566

def exception_middleware(self) -> list:

567

"""Exception middleware list."""

568

569

@property

570

def error_handler(self):

571

"""Application error handler."""

572

573

@property

574

def name(self) -> str:

575

"""Application name."""

576

577

@property

578

def strict_slashes(self) -> bool:

579

"""Strict slash handling setting."""

580

581

@property

582

def is_running(self) -> bool:

583

"""Whether server is currently running."""

584

585

@property

586

def is_request_stream(self) -> bool:

587

"""Whether request streaming is enabled."""

588

```

589

590

## Usage Examples

591

592

### Basic Application Setup

593

594

```python

595

from sanic import Sanic

596

from sanic.response import json

597

598

app = Sanic("MyApplication")

599

600

@app.route("/api/users/<user_id:int>")

601

async def get_user(request, user_id):

602

# Fetch user from database

603

user = await fetch_user(user_id)

604

return json({"user": user})

605

606

@app.route("/api/users", methods=["POST"])

607

async def create_user(request):

608

user_data = request.json

609

user = await create_user(user_data)

610

return json({"user": user}, status=201)

611

612

if __name__ == "__main__":

613

app.run(host="0.0.0.0", port=8000, workers=4)

614

```

615

616

### Advanced Configuration

617

618

```python

619

from sanic import Sanic

620

from sanic.config import Config

621

622

# Custom configuration

623

config = Config()

624

config.REQUEST_TIMEOUT = 60

625

config.RESPONSE_TIMEOUT = 60

626

config.KEEP_ALIVE_TIMEOUT = 5

627

628

app = Sanic("MyApp", config=config)

629

630

# Environment-based configuration

631

app.config.load_environment_vars("MYAPP_")

632

633

# SSL configuration

634

ssl_config = {

635

"cert": "/path/to/cert.pem",

636

"key": "/path/to/key.pem"

637

}

638

639

app.run(host="0.0.0.0", port=8443, ssl=ssl_config)

640

```

641

642

### Event Listeners and Lifecycle

643

644

```python

645

@app.before_server_start

646

async def setup_database(app, loop):

647

"""Initialize database connection."""

648

app.ctx.db = await create_database_connection()

649

650

@app.after_server_start

651

async def notify_ready(app, loop):

652

"""Notify that server is ready."""

653

print(f"Server ready at http://{app.config.HOST}:{app.config.PORT}")

654

655

@app.before_server_stop

656

async def cleanup(app, loop):

657

"""Clean up resources."""

658

await app.ctx.db.close()

659

```