or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

blueprints.mdcli.mdconfiguration.mdcontext-globals.mdcore-application.mdhelpers.mdindex.mdjson-support.mdrequest-response.mdrouting.mdsessions.mdsignals.mdtemplates.mdtesting.md

core-application.mddocs/

0

# Core Application

1

2

The Flask application class provides the central registry for views, URL rules, template configuration and much more. It implements a WSGI application and serves as the main entry point for Flask web applications.

3

4

## Capabilities

5

6

### Flask Application Class

7

8

The main application class that implements a WSGI application and acts as the central registry for routing, configuration, and extensions.

9

10

```python { .api }

11

class Flask:

12

def __init__(

13

self,

14

import_name: str,

15

static_url_path: str | None = None,

16

static_folder: str | os.PathLike[str] | None = "static",

17

static_host: str | None = None,

18

host_matching: bool = False,

19

subdomain_matching: bool = False,

20

template_folder: str | os.PathLike[str] | None = "templates",

21

instance_path: str | None = None,

22

instance_relative_config: bool = False,

23

root_path: str | None = None,

24

):

25

"""

26

Create a Flask application.

27

28

Args:

29

import_name: Name of the application package (usually __name__)

30

static_url_path: URL path for static files (defaults to '/static')

31

static_folder: Folder containing static files relative to app

32

static_host: Host to use when generating static file URLs

33

host_matching: Enable host matching for URLs

34

subdomain_matching: Enable subdomain matching for URLs

35

template_folder: Folder containing templates relative to app

36

instance_path: Path to instance folder for configuration/data files

37

instance_relative_config: Load config relative to instance path

38

root_path: Path to the root of the application

39

"""

40

```

41

42

### Application Properties

43

44

Core properties available on Flask application instances.

45

46

```python { .api }

47

class Flask:

48

# Application identification

49

name: str # Application name

50

import_name: str # Import name passed to constructor

51

52

# Configuration and debugging

53

config: Config # Configuration dictionary

54

debug: bool # Debug mode flag

55

testing: bool # Testing mode flag

56

secret_key: str | bytes | None # Secret key for sessions/cookies

57

58

# Template and static file handling

59

jinja_env: Environment # Jinja2 environment

60

static_folder: str | None # Static files folder path

61

static_url_path: str | None # URL path for static files

62

template_folder: str | None # Templates folder path

63

64

# URL routing

65

url_map: Map # URL routing map

66

view_functions: dict[str, Callable] # Registered view functions

67

68

# Request handling

69

before_request_funcs: dict # Before request handlers

70

after_request_funcs: dict # After request handlers

71

teardown_request_funcs: dict # Request teardown handlers

72

teardown_appcontext_funcs: list # App context teardown handlers

73

74

# Extensions and customization

75

extensions: dict # Registered extensions

76

blueprints: dict[str, Blueprint] # Registered blueprints

77

json: JSONProvider # JSON provider instance

78

79

# Session configuration

80

permanent_session_lifetime: timedelta # Permanent session lifetime

81

session_interface: SessionInterface # Session interface

82

83

# Error handling

84

error_handler_spec: dict # Error handler specifications

85

86

# Logging

87

logger: Logger # Application logger

88

```

89

90

### Application Lifecycle Methods

91

92

Methods for running and managing the Flask application lifecycle.

93

94

```python { .api }

95

def run(

96

self,

97

host: str | None = None,

98

port: int | None = None,

99

debug: bool | None = None,

100

load_dotenv: bool = True,

101

**options

102

) -> None:

103

"""

104

Run the application using the development server.

105

106

Args:

107

host: Hostname to listen on (defaults to '127.0.0.1')

108

port: Port to listen on (defaults to 5000)

109

debug: Enable debug mode

110

load_dotenv: Load environment variables from .env file

111

**options: Additional options passed to werkzeug server

112

"""

113

114

def wsgi_app(self, environ: dict, start_response: Callable) -> Iterator[bytes]:

115

"""

116

The actual WSGI application called by the WSGI server.

117

118

Args:

119

environ: WSGI environment dictionary

120

start_response: WSGI start_response callable

121

122

Returns:

123

Iterator of response bytes

124

"""

125

```

126

127

### Context Management

128

129

Methods for creating and managing application and request contexts.

130

131

```python { .api }

132

def app_context(self) -> AppContext:

133

"""

134

Create an application context.

135

136

Returns:

137

Application context manager

138

"""

139

140

def request_context(self, environ: dict) -> RequestContext:

141

"""

142

Create a request context from WSGI environment.

143

144

Args:

145

environ: WSGI environment dictionary

146

147

Returns:

148

Request context manager

149

"""

150

151

def test_request_context(self, *args, **kwargs) -> RequestContext:

152

"""

153

Create a request context for testing.

154

155

Args:

156

*args: Arguments passed to EnvironBuilder

157

**kwargs: Keyword arguments passed to EnvironBuilder

158

159

Returns:

160

Request context manager for testing

161

"""

162

```

163

164

### Testing Support

165

166

Methods for creating test clients and runners for application testing.

167

168

```python { .api }

169

def test_client(self, use_cookies: bool = True, **kwargs) -> FlaskClient:

170

"""

171

Create a test client for the application.

172

173

Args:

174

use_cookies: Enable cookie support in test client

175

**kwargs: Additional arguments passed to test client class

176

177

Returns:

178

Test client instance

179

"""

180

181

def test_cli_runner(self, **kwargs) -> FlaskCliRunner:

182

"""

183

Create a CLI test runner for the application.

184

185

Args:

186

**kwargs: Additional arguments passed to CLI runner

187

188

Returns:

189

CLI test runner instance

190

"""

191

```

192

193

### Response Creation

194

195

Methods for creating and processing responses.

196

197

```python { .api }

198

def make_response(self, rv) -> Response:

199

"""

200

Convert a return value to a Response object.

201

202

Args:

203

rv: Return value (str, bytes, dict, list, tuple, Response, etc.)

204

205

Returns:

206

Response object

207

"""

208

209

def make_default_options_response(self) -> Response:

210

"""

211

Create a default OPTIONS response.

212

213

Returns:

214

Response with allowed methods in Allow header

215

"""

216

```

217

218

### Request Processing

219

220

Methods for handling request processing lifecycle.

221

222

```python { .api }

223

def dispatch_request(self) -> ResponseReturnValue:

224

"""

225

Match the URL and dispatch to view function.

226

227

Returns:

228

Return value from view function

229

"""

230

231

def full_dispatch_request(self) -> Response:

232

"""

233

Complete request dispatch with pre/post processing.

234

235

Returns:

236

Final response object

237

"""

238

239

def preprocess_request(self) -> ResponseReturnValue | None:

240

"""

241

Run before_request handlers.

242

243

Returns:

244

Response if handler returned one, None otherwise

245

"""

246

247

def process_response(self, response: Response) -> Response:

248

"""

249

Run after_request handlers on response.

250

251

Args:

252

response: Response object to process

253

254

Returns:

255

Processed response object

256

"""

257

258

def finalize_request(

259

self,

260

rv: ResponseReturnValue,

261

from_error_handler: bool = False

262

) -> Response:

263

"""

264

Convert return value to Response and finalize.

265

266

Args:

267

rv: Return value from view or error handler

268

from_error_handler: Whether rv came from error handler

269

270

Returns:

271

Final response object

272

"""

273

```

274

275

### Error Handling

276

277

Methods for handling exceptions and HTTP errors.

278

279

```python { .api }

280

def handle_exception(self, e: Exception) -> Response:

281

"""

282

Handle any uncaught exception.

283

284

Args:

285

e: Exception that was raised

286

287

Returns:

288

Error response

289

"""

290

291

def handle_http_exception(self, e: HTTPException) -> Response:

292

"""

293

Handle HTTP exceptions.

294

295

Args:

296

e: HTTP exception

297

298

Returns:

299

Error response

300

"""

301

302

def handle_user_exception(self, e: Exception) -> Response:

303

"""

304

Handle exceptions in user code.

305

306

Args:

307

e: Exception from user code

308

309

Returns:

310

Error response

311

"""

312

313

def log_exception(self, exc_info) -> None:

314

"""

315

Log an exception to the application logger.

316

317

Args:

318

exc_info: Exception info tuple

319

"""

320

```

321

322

### Static File Handling

323

324

Methods for serving static files.

325

326

```python { .api }

327

def send_static_file(self, filename: str) -> Response:

328

"""

329

Send a static file from the static folder.

330

331

Args:

332

filename: Filename relative to static folder

333

334

Returns:

335

Response with file contents

336

"""

337

338

def get_send_file_max_age(self, filename: str | None) -> int | None:

339

"""

340

Get max age for static file caching.

341

342

Args:

343

filename: Static filename

344

345

Returns:

346

Max age in seconds or None

347

"""

348

```

349

350

### Shell Context

351

352

Methods for customizing the interactive shell context.

353

354

```python { .api }

355

def make_shell_context(self) -> dict[str, Any]:

356

"""

357

Create shell context with application globals.

358

359

Returns:

360

Dictionary of names available in shell

361

"""

362

363

def shell_context_processor(self, f: Callable) -> Callable:

364

"""

365

Decorator to register shell context processor.

366

367

Args:

368

f: Function that returns dict of shell context variables

369

370

Returns:

371

The original function

372

"""

373

```

374

375

## Usage Examples

376

377

### Basic Application Setup

378

379

```python

380

from flask import Flask

381

382

# Create application

383

app = Flask(__name__)

384

app.secret_key = 'your-secret-key-here'

385

386

# Configure application

387

app.config['DEBUG'] = True

388

app.config['TESTING'] = False

389

390

# Basic route

391

@app.route('/')

392

def home():

393

return 'Hello World!'

394

395

# Run application

396

if __name__ == '__main__':

397

app.run(host='0.0.0.0', port=8000, debug=True)

398

```

399

400

### Application with Custom Configuration

401

402

```python

403

from flask import Flask

404

import os

405

406

# Create application with custom folders

407

app = Flask(

408

__name__,

409

static_folder='assets',

410

static_url_path='/assets',

411

template_folder='templates'

412

)

413

414

# Load configuration

415

app.config.from_object('config.DevelopmentConfig')

416

app.config.from_envvar('APP_SETTINGS', silent=True)

417

418

# Set up logging

419

if not app.debug:

420

import logging

421

from logging.handlers import RotatingFileHandler

422

423

file_handler = RotatingFileHandler('app.log', maxBytes=10240, backupCount=10)

424

file_handler.setFormatter(logging.Formatter(

425

'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'

426

))

427

file_handler.setLevel(logging.INFO)

428

app.logger.addHandler(file_handler)

429

app.logger.setLevel(logging.INFO)

430

```

431

432

### Testing Setup

433

434

```python

435

import pytest

436

from flask import Flask

437

438

@pytest.fixture

439

def app():

440

app = Flask(__name__)

441

app.config['TESTING'] = True

442

app.config['SECRET_KEY'] = 'test-key'

443

444

@app.route('/')

445

def index():

446

return 'Hello Test!'

447

448

return app

449

450

@pytest.fixture

451

def client(app):

452

return app.test_client()

453

454

@pytest.fixture

455

def runner(app):

456

return app.test_cli_runner()

457

458

def test_index(client):

459

response = client.get('/')

460

assert response.status_code == 200

461

assert response.data == b'Hello Test!'

462

```