0
# Framework Integrations
1
2
Raven provides comprehensive integrations with popular Python web frameworks, offering automatic error capture, request context, and framework-specific features.
3
4
## Capabilities
5
6
### Django Integration
7
8
Enhanced Sentry client with Django-specific features and automatic integration.
9
10
```python { .api }
11
from raven.contrib.django.client import DjangoClient
12
13
class DjangoClient(Client):
14
def __init__(self, **kwargs):
15
"""
16
Django-enhanced Sentry client.
17
Automatically reads configuration from Django settings.
18
"""
19
20
def get_client(client=None, reset=False):
21
"""
22
Get configured Django Sentry client.
23
24
Parameters:
25
- client (str): Client class path override
26
- reset (bool): Reset cached client instance
27
28
Returns:
29
DjangoClient: Configured client instance
30
"""
31
32
def sentry_exception_handler(sender, **kwargs):
33
"""
34
Django signal handler for exception capture.
35
36
Parameters:
37
- sender: Signal sender
38
- **kwargs: Signal arguments including request
39
"""
40
```
41
42
#### Django Middleware
43
44
```python { .api }
45
from raven.contrib.django.middleware import SentryMiddleware, Sentry404CatchMiddleware, SentryResponseErrorIdMiddleware
46
47
class SentryMiddleware:
48
"""General Sentry middleware for Django requests."""
49
def process_exception(self, request, exception): ...
50
51
class Sentry404CatchMiddleware:
52
"""Middleware to capture 404 errors."""
53
def process_response(self, request, response): ...
54
55
class SentryResponseErrorIdMiddleware:
56
"""Middleware to add Sentry error ID to responses."""
57
def process_response(self, request, response): ...
58
```
59
60
#### Django Logging Handler
61
62
```python { .api }
63
from raven.contrib.django.handlers import SentryHandler
64
65
class SentryHandler(logging.Handler):
66
"""Django-specific Sentry logging handler."""
67
def __init__(self, **kwargs):
68
"""
69
Initialize handler with Django settings integration.
70
"""
71
```
72
73
### Flask Integration
74
75
Seamless Flask application integration with automatic error capture and request context.
76
77
```python { .api }
78
from raven.contrib.flask import Sentry
79
80
class Sentry:
81
def __init__(self, app=None, client=None, client_cls=None, dsn=None,
82
logging=None, level=logging.ERROR, logging_exclusions=None,
83
wrap_wsgi=None, register_signal=True, **kwargs):
84
"""
85
Flask Sentry integration.
86
87
Parameters:
88
- app (Flask): Flask application instance
89
- client (Client): Custom client instance
90
- client_cls (type): Custom client class
91
- dsn (str): Sentry DSN override
92
- logging (bool): Enable logging integration
93
- level (int): Minimum logging level
94
- logging_exclusions (tuple): Excluded logger names
95
- wrap_wsgi (bool): Wrap WSGI application
96
- register_signal (bool): Register Flask error signal
97
"""
98
99
def init_app(self, app, dsn=None, **kwargs):
100
"""
101
Initialize Sentry for Flask app.
102
103
Parameters:
104
- app (Flask): Flask application
105
- dsn (str): Sentry DSN
106
- **kwargs: Additional configuration
107
"""
108
109
def captureException(self, exc_info=None, **kwargs):
110
"""Capture exception with Flask request context."""
111
112
def captureMessage(self, message, **kwargs):
113
"""Capture message with Flask request context."""
114
```
115
116
### Bottle Integration
117
118
```python { .api }
119
from raven.contrib.bottle import Sentry
120
121
class Sentry:
122
def __init__(self, app, client=None, **kwargs):
123
"""
124
Bottle Sentry integration.
125
126
Parameters:
127
- app: Bottle application instance
128
- client (Client): Custom client instance
129
"""
130
```
131
132
### Celery Integration
133
134
Automatic error capture for Celery task execution.
135
136
```python { .api }
137
from raven.contrib.celery import SentryCeleryHandler, register_signal, register_logger_signal
138
139
def register_signal(client, ignore_expected=False):
140
"""
141
Register Celery signal handler for task failures.
142
143
Parameters:
144
- client (Client): Sentry client instance
145
- ignore_expected (bool): Ignore expected task failures
146
"""
147
148
def register_logger_signal(client, logger=None, loglevel=logging.ERROR):
149
"""
150
Register Celery logger signal handler.
151
152
Parameters:
153
- client (Client): Sentry client instance
154
- logger (str): Logger name
155
- loglevel (int): Minimum log level
156
"""
157
158
class SentryCeleryHandler:
159
def __init__(self, client):
160
"""
161
Celery task failure handler.
162
163
Parameters:
164
- client (Client): Sentry client instance
165
"""
166
```
167
168
### Tornado Integration
169
170
Asynchronous Sentry client for Tornado applications.
171
172
```python { .api }
173
from raven.contrib.tornado import AsyncSentryClient
174
175
class AsyncSentryClient(Client):
176
def __init__(self, **kwargs):
177
"""
178
Tornado async Sentry client.
179
Uses Tornado's async HTTP client for non-blocking sends.
180
"""
181
182
def send(self, **data):
183
"""
184
Send event asynchronously.
185
186
Returns:
187
tornado.concurrent.Future: Async send operation
188
"""
189
```
190
191
### Pylons Integration
192
193
```python { .api }
194
from raven.contrib.pylons import Sentry
195
196
class Sentry:
197
def __init__(self, config, client_cls=None):
198
"""
199
Pylons Sentry integration.
200
201
Parameters:
202
- config (dict): Pylons configuration
203
- client_cls (type): Custom client class
204
"""
205
```
206
207
### AWS Lambda Integration
208
209
Specialized client for serverless AWS Lambda functions.
210
211
```python { .api }
212
from raven.contrib.awslambda import LambdaClient
213
214
class LambdaClient(Client):
215
def __init__(self, **kwargs):
216
"""
217
AWS Lambda optimized Sentry client.
218
Handles Lambda-specific context and constraints.
219
"""
220
```
221
222
### Sanic Integration
223
224
Modern async web framework integration.
225
226
```python { .api }
227
from raven.contrib.sanic import Sentry
228
229
class Sentry:
230
def __init__(self, app=None, **kwargs):
231
"""
232
Sanic Sentry integration.
233
234
Parameters:
235
- app: Sanic application instance
236
"""
237
```
238
239
### Web.py Integration
240
241
Integration for the web.py web framework.
242
243
```python { .api }
244
from raven.contrib.webpy import SentryApplication
245
246
class SentryApplication(web.application):
247
def __init__(self, client, mapping=None, fvars=None, logging=False,
248
level=logging.ERROR, **kwargs):
249
"""
250
Web.py application with Sentry integration.
251
252
Parameters:
253
- client (Client): Sentry client instance
254
- mapping: URL mapping
255
- fvars: Global variables
256
- logging (bool): Enable automatic logging integration
257
- level (int): Minimum logging level
258
"""
259
```
260
261
### Paste Integration
262
263
WSGI middleware integration for Paste framework.
264
265
```python { .api }
266
from raven.contrib.paste import sentry_filter_factory
267
268
def sentry_filter_factory(app, global_conf, **kwargs):
269
"""
270
Factory function for Paste/WSGI integration.
271
272
Parameters:
273
- app: WSGI application
274
- global_conf (dict): Global configuration
275
- **kwargs: Client configuration options
276
277
Returns:
278
callable: WSGI middleware
279
"""
280
```
281
282
### ZeroRPC Integration
283
284
Middleware for ZeroRPC distributed computing framework.
285
286
```python { .api }
287
from raven.contrib.zerorpc import SentryMiddleware
288
289
class SentryMiddleware:
290
def __init__(self, hide_zerorpc_frames=True, client=None, **kwargs):
291
"""
292
ZeroRPC middleware for automatic exception capture.
293
294
Parameters:
295
- hide_zerorpc_frames (bool): Hide ZeroRPC internal frames from stack traces
296
- client (Client): Existing Sentry client instance
297
- **kwargs: Client configuration options
298
"""
299
```
300
301
### Zope Integration
302
303
Integration for Zope web application framework.
304
305
```python { .api }
306
from raven.contrib.zope import ZopeSentryHandler
307
308
class ZopeSentryHandler:
309
def __init__(self, dsn=None, **kwargs):
310
"""
311
Zope exception handler for Sentry integration.
312
313
Parameters:
314
- dsn (str): Sentry DSN
315
- **kwargs: Client configuration options
316
"""
317
```
318
319
### ZConfig Integration
320
321
Configuration integration for ZConfig-based applications.
322
323
```python { .api }
324
from raven.contrib.zconfig import logger_factory
325
326
def logger_factory():
327
"""
328
ZConfig logger factory for Sentry integration.
329
"""
330
```
331
332
## Usage Examples
333
334
### Django Setup
335
336
```python
337
# settings.py
338
INSTALLED_APPS = [
339
'raven.contrib.django',
340
# ... other apps
341
]
342
343
RAVEN_CONFIG = {
344
'dsn': 'https://your-dsn@sentry.io/project-id',
345
'release': '1.0.0',
346
'environment': 'production',
347
}
348
349
MIDDLEWARE = [
350
'raven.contrib.django.middleware.SentryMiddleware',
351
# ... other middleware
352
]
353
354
LOGGING = {
355
'version': 1,
356
'handlers': {
357
'sentry': {
358
'level': 'ERROR',
359
'class': 'raven.contrib.django.handlers.SentryHandler',
360
},
361
},
362
'loggers': {
363
'root': {
364
'handlers': ['sentry'],
365
},
366
}
367
}
368
369
# Usage in views
370
from raven.contrib.django.models import client
371
372
def my_view(request):
373
try:
374
risky_operation()
375
except Exception:
376
client.captureException()
377
return HttpResponse('Error occurred')
378
```
379
380
### Flask Setup
381
382
```python
383
from flask import Flask
384
from raven.contrib.flask import Sentry
385
386
app = Flask(__name__)
387
app.config['SENTRY_DSN'] = 'https://your-dsn@sentry.io/project-id'
388
389
sentry = Sentry(app)
390
391
@app.route('/error')
392
def error():
393
try:
394
1/0
395
except ZeroDivisionError:
396
sentry.captureException()
397
return 'Error captured!'
398
399
@app.route('/message')
400
def message():
401
sentry.captureMessage('User accessed message endpoint')
402
return 'Message sent to Sentry'
403
```
404
405
### Celery Setup
406
407
```python
408
from celery import Celery
409
from raven.contrib.celery import register_signal, register_logger_signal
410
from raven import Client
411
412
client = Client('https://your-dsn@sentry.io/project-id')
413
414
# Register signal handlers
415
register_signal(client)
416
register_logger_signal(client)
417
418
app = Celery('myapp')
419
420
@app.task
421
def risky_task():
422
# Any exception will be automatically captured
423
return 1/0
424
```
425
426
### Tornado Setup
427
428
```python
429
import tornado.web
430
from raven.contrib.tornado import AsyncSentryClient
431
432
class MainHandler(tornado.web.RequestHandler):
433
def initialize(self):
434
self.sentry = AsyncSentryClient('https://your-dsn@sentry.io/project-id')
435
436
async def get(self):
437
try:
438
await some_async_operation()
439
except Exception:
440
await self.sentry.captureException()
441
self.write('Error occurred')
442
```
443
444
### Web.py Setup
445
446
```python
447
import web
448
from raven import Client
449
from raven.contrib.webpy import SentryApplication
450
451
urls = (
452
'/', 'index',
453
'/error', 'error'
454
)
455
456
client = Client('https://your-dsn@sentry.io/project-id')
457
458
class index:
459
def GET(self):
460
return "Hello, World!"
461
462
class error:
463
def GET(self):
464
raise Exception("Test error")
465
466
# Create application with Sentry integration
467
app = SentryApplication(client, mapping=urls, fvars=globals(), logging=True)
468
469
if __name__ == "__main__":
470
app.run()
471
```
472
473
### ZeroRPC Setup
474
475
```python
476
import zerorpc
477
from raven.contrib.zerorpc import SentryMiddleware
478
479
# Set up Sentry middleware
480
sentry = SentryMiddleware(dsn='https://your-dsn@sentry.io/project-id')
481
zerorpc.Context.get_instance().register_middleware(sentry)
482
483
class HelloRPC:
484
def hello(self):
485
return "Hello World"
486
487
def error(self):
488
# This exception will be automatically captured
489
raise Exception("RPC error occurred")
490
491
s = zerorpc.Server(HelloRPC())
492
s.bind("tcp://0.0.0.0:4242")
493
s.run()
494
```
495
496
### Paste Configuration
497
498
```ini
499
# In your Paste configuration file (development.ini, production.ini, etc.)
500
[filter:sentry]
501
use = egg:raven#sentry
502
dsn = https://your-dsn@sentry.io/project-id
503
include_paths = myapp
504
level = WARN
505
506
[pipeline:main]
507
pipeline = sentry myapp
508
509
[app:myapp]
510
use = egg:MyApp
511
```