or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-routing.mdindex.mdplugin-system.mdrequest-handling.mdresponse-management.mdserver-management.mdstatic-utilities.mdtemplate-rendering.md

response-management.mddocs/

0

# Response Management

1

2

Response object for setting HTTP response properties including status codes, headers, cookies, content type, and response body handling.

3

4

## Capabilities

5

6

### Response Object

7

8

The global response object allows modification of HTTP response properties.

9

10

```python { .api }

11

response: LocalResponse

12

"""Global thread-local response instance available in route handlers."""

13

```

14

15

### Response Properties

16

17

Set basic HTTP response properties.

18

19

```python { .api }

20

class BaseResponse:

21

@property

22

def status(self) -> int:

23

"""HTTP status code (200, 404, 500, etc.)."""

24

25

@status.setter

26

def status(self, value: int):

27

"""Set HTTP status code."""

28

29

@property

30

def status_line(self) -> str:

31

"""Full HTTP status line (e.g., '200 OK')."""

32

33

@property

34

def status_code(self) -> int:

35

"""Alias for status property."""

36

37

@property

38

def headers(self) -> HeaderDict:

39

"""Response headers as HeaderDict."""

40

41

@property

42

def headerlist(self) -> list:

43

"""Response headers as list of (name, value) tuples."""

44

45

@property

46

def content_type(self) -> str:

47

"""Content-Type header value."""

48

49

@content_type.setter

50

def content_type(self, value: str):

51

"""Set Content-Type header."""

52

53

@property

54

def content_length(self) -> int:

55

"""Content-Length header value."""

56

57

@content_length.setter

58

def content_length(self, value: int):

59

"""Set Content-Length header."""

60

61

@property

62

def charset(self) -> str:

63

"""Character encoding from Content-Type."""

64

65

@charset.setter

66

def charset(self, value: str):

67

"""Set character encoding in Content-Type."""

68

```

69

70

### Header Management

71

72

Add, set, and retrieve response headers.

73

74

```python { .api }

75

class BaseResponse:

76

def set_header(self, name, value):

77

"""

78

Set response header, replacing any existing values.

79

80

Parameters:

81

- name: str, header name

82

- value: str, header value

83

"""

84

85

def add_header(self, name, value):

86

"""

87

Add response header, preserving existing values.

88

89

Parameters:

90

- name: str, header name

91

- value: str, header value

92

"""

93

94

def get_header(self, name, default=None):

95

"""

96

Get response header value.

97

98

Parameters:

99

- name: str, header name (case-insensitive)

100

- default: any, default value if header not found

101

102

Returns:

103

str or default: header value

104

"""

105

106

def iter_headers(self):

107

"""Iterate over all response headers as (name, value) tuples."""

108

```

109

110

Usage:

111

112

```python

113

@route('/api/data')

114

def api_data():

115

response.content_type = 'application/json'

116

response.set_header('X-API-Version', '1.0')

117

response.add_header('X-Custom', 'value1')

118

response.add_header('X-Custom', 'value2') # Multiple values

119

return '{"data": "example"}'

120

```

121

122

### Cookie Management

123

124

Set and delete response cookies with various options.

125

126

```python { .api }

127

class BaseResponse:

128

def set_cookie(self, key, value, max_age=None, expires=None, domain=None, path='/', secure=False, httponly=False, samesite=None, secret=None, digestmod=hashlib.sha256):

129

"""

130

Set a response cookie.

131

132

Parameters:

133

- key: str, cookie name

134

- value: str, cookie value

135

- max_age: int, cookie lifetime in seconds

136

- expires: datetime or str, cookie expiration time

137

- domain: str, cookie domain

138

- path: str, cookie path (default: '/')

139

- secure: bool, require HTTPS

140

- httponly: bool, prevent JavaScript access

141

- samesite: str, SameSite attribute ('Strict', 'Lax', 'None')

142

- secret: str, secret for signed cookies

143

- digestmod: hashlib algorithm for signing

144

"""

145

146

def delete_cookie(self, key, **kwargs):

147

"""

148

Delete a cookie by setting it to expire.

149

150

Parameters:

151

- key: str, cookie name

152

- **kwargs: same domain/path options as set_cookie

153

"""

154

```

155

156

Usage:

157

158

```python

159

@route('/login', method='POST')

160

def login():

161

# Set regular cookie

162

response.set_cookie('user_id', '123', max_age=3600)

163

164

# Set secure, httponly cookie

165

response.set_cookie('session', 'abc123',

166

secure=True, httponly=True,

167

samesite='Strict')

168

169

# Set signed cookie

170

response.set_cookie('auth_token', 'token123',

171

secret='my-secret-key')

172

173

return 'Logged in'

174

175

@route('/logout')

176

def logout():

177

response.delete_cookie('user_id')

178

response.delete_cookie('session')

179

return 'Logged out'

180

```

181

182

### Response Body

183

184

Handle response body content and encoding.

185

186

```python { .api }

187

class BaseResponse:

188

@property

189

def body(self):

190

"""Response body content."""

191

192

@body.setter

193

def body(self, value):

194

"""Set response body content."""

195

```

196

197

## HTTP Response Exceptions

198

199

Raise HTTP responses as exceptions for flow control.

200

201

### HTTPResponse

202

203

Base HTTP response exception that can be raised to return a response.

204

205

```python { .api }

206

class HTTPResponse(Exception):

207

def __init__(self, body='', status=None, headers=None, **more_headers):

208

"""

209

Create HTTP response exception.

210

211

Parameters:

212

- body: str or bytes, response body

213

- status: int, HTTP status code

214

- headers: dict, response headers

215

- **more_headers: additional headers as keyword arguments

216

"""

217

218

@property

219

def status(self) -> int:

220

"""HTTP status code."""

221

222

@property

223

def status_line(self) -> str:

224

"""HTTP status line."""

225

226

@property

227

def body(self):

228

"""Response body."""

229

230

@property

231

def headers(self) -> HeaderDict:

232

"""Response headers."""

233

234

def set_header(self, name, value):

235

"""Set response header."""

236

237

def add_header(self, name, value):

238

"""Add response header."""

239

```

240

241

### HTTPError

242

243

HTTP error response exception.

244

245

```python { .api }

246

class HTTPError(HTTPResponse):

247

def __init__(self, status=500, body=None, exception=None, traceback=None, **more_headers):

248

"""

249

Create HTTP error response.

250

251

Parameters:

252

- status: int, HTTP error status code

253

- body: str, error response body

254

- exception: Exception, original exception

255

- traceback: str, exception traceback

256

- **more_headers: additional headers

257

"""

258

```

259

260

## Response Utilities

261

262

### Abort and Redirect

263

264

Utility functions for common HTTP responses.

265

266

```python { .api }

267

def abort(code=500, text='Unknown Error.'):

268

"""

269

Raise HTTPError with specified status code.

270

271

Parameters:

272

- code: int, HTTP status code

273

- text: str, error message

274

275

Raises:

276

HTTPError: HTTP error response

277

"""

278

279

def redirect(url, code=None):

280

"""

281

Raise HTTPResponse that redirects to URL.

282

283

Parameters:

284

- url: str, redirect URL

285

- code: int, HTTP redirect status code (302 default)

286

287

Raises:

288

HTTPResponse: redirect response

289

"""

290

```

291

292

Usage:

293

294

```python

295

@route('/admin')

296

def admin():

297

if not user_is_admin():

298

abort(403, 'Access denied')

299

return 'Admin panel'

300

301

@route('/old-page')

302

def old_page():

303

redirect('/new-page', code=301) # Permanent redirect

304

305

@route('/login-required')

306

def protected():

307

if not logged_in():

308

redirect('/login')

309

return 'Protected content'

310

```

311

312

### Static File Responses

313

314

Serve static files with proper headers and caching.

315

316

```python { .api }

317

def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):

318

"""

319

Serve static file with proper MIME type and caching headers.

320

321

Parameters:

322

- filename: str, file name to serve

323

- root: str, root directory path

324

- mimetype: str, MIME type ('auto' for detection)

325

- download: bool, force download with Content-Disposition

326

- charset: str, character encoding for text files

327

328

Returns:

329

HTTPResponse: file response with proper headers

330

331

Raises:

332

HTTPError: 404 if file not found, 403 if access denied

333

"""

334

```

335

336

Usage:

337

338

```python

339

@route('/static/<filepath:path>')

340

def serve_static(filepath):

341

return static_file(filepath, root='/var/www/static/')

342

343

@route('/download/<filename>')

344

def download_file(filename):

345

return static_file(filename, root='/var/downloads/',

346

download=True)

347

348

@route('/images/<filename>')

349

def serve_image(filename):

350

return static_file(filename, root='/var/images/',

351

mimetype='image/jpeg')

352

```

353

354

## Response Context

355

356

### WSGI Integration

357

358

Response objects integrate with WSGI for server compatibility.

359

360

```python { .api }

361

class BaseResponse:

362

def __iter__(self):

363

"""Iterate over response body chunks."""

364

365

def close(self):

366

"""Clean up response resources."""

367

368

def __enter__(self):

369

"""Context manager entry."""

370

371

def __exit__(self, exc_type, exc_val, exc_tb):

372

"""Context manager exit."""

373

```

374

375

### Response Binding

376

377

Response objects can be bound to specific requests.

378

379

```python { .api }

380

class LocalResponse(BaseResponse):

381

"""Thread-local response instance."""

382

383

def bind(self, environ):

384

"""Bind response to WSGI environ."""

385

```