0
# Transport Layer
1
2
Raven provides multiple transport implementations for sending events to Sentry servers, supporting different execution environments and performance requirements from synchronous blocking to fully asynchronous.
3
4
## Capabilities
5
6
### Base Transport Classes
7
8
Foundation classes for all transport implementations.
9
10
```python { .api }
11
from raven.transport.base import Transport, AsyncTransport
12
13
class Transport:
14
def __init__(self, parsed_url, timeout=None):
15
"""
16
Base transport class.
17
18
Parameters:
19
- parsed_url: Parsed Sentry DSN URL
20
- timeout (int): Request timeout in seconds
21
"""
22
23
def send(self, url, data, headers):
24
"""
25
Send event data to Sentry.
26
27
Parameters:
28
- url (str): Sentry endpoint URL
29
- data (str): Encoded event data
30
- headers (dict): HTTP headers
31
32
Returns:
33
str: Event ID
34
"""
35
36
class AsyncTransport(Transport):
37
"""Base class for asynchronous transports."""
38
39
def async_send(self, url, data, headers, success_cb, failure_cb):
40
"""
41
Send event data asynchronously.
42
43
Parameters:
44
- url (str): Sentry endpoint URL
45
- data (str): Encoded event data
46
- headers (dict): HTTP headers
47
- success_cb (callable): Success callback
48
- failure_cb (callable): Failure callback
49
"""
50
```
51
52
### HTTP Transport
53
54
Standard synchronous HTTP transport using Python's built-in urllib.
55
56
```python { .api }
57
from raven.transport.http import HTTPTransport
58
59
class HTTPTransport(Transport):
60
scheme = ['sync+http', 'sync+https']
61
62
def __init__(self, timeout=5, verify_ssl=True, ca_certs=None):
63
"""
64
Synchronous HTTP transport.
65
66
Parameters:
67
- timeout (int): Request timeout in seconds
68
- verify_ssl (bool): Verify SSL certificates
69
- ca_certs (str): Path to CA certificate bundle
70
"""
71
```
72
73
### Threaded HTTP Transport
74
75
HTTP transport with background thread for non-blocking sends.
76
77
```python { .api }
78
from raven.transport.threaded import ThreadedHTTPTransport
79
80
class ThreadedHTTPTransport(AsyncTransport, HTTPTransport):
81
scheme = ['http', 'https', 'threaded+http', 'threaded+https']
82
83
def __init__(self, timeout=5, verify_ssl=True, ca_certs=None):
84
"""
85
Threaded HTTP transport for non-blocking sends.
86
Inherits constructor from HTTPTransport.
87
88
Parameters:
89
- timeout (int): Request timeout in seconds
90
- verify_ssl (bool): Verify SSL certificates
91
- ca_certs (str): Path to CA certificate bundle
92
"""
93
```
94
95
### Requests-Based Transport
96
97
HTTP transport using the requests library for enhanced features.
98
99
```python { .api }
100
from raven.transport.requests import RequestsHTTPTransport, ThreadedRequestsHTTPTransport
101
102
class RequestsHTTPTransport(Transport):
103
def __init__(self, parsed_url, timeout=5, verify_ssl=True, ca_certs=None):
104
"""
105
HTTP transport using requests library.
106
107
Parameters:
108
- parsed_url: Parsed Sentry DSN URL
109
- timeout (int): Request timeout in seconds
110
- verify_ssl (bool): Verify SSL certificates
111
- ca_certs (str): Path to CA certificate bundle
112
"""
113
114
class ThreadedRequestsHTTPTransport(AsyncTransport):
115
"""Threaded version of requests-based transport."""
116
```
117
118
### Gevent Transport
119
120
Asynchronous transport for gevent-based applications.
121
122
```python { .api }
123
from raven.transport.gevent import GeventedHTTPTransport
124
125
class GeventedHTTPTransport(AsyncTransport):
126
def __init__(self, parsed_url, timeout=5, pool_size=10):
127
"""
128
Gevent-based async HTTP transport.
129
130
Parameters:
131
- parsed_url: Parsed Sentry DSN URL
132
- timeout (int): Request timeout in seconds
133
- pool_size (int): Gevent pool size
134
"""
135
```
136
137
### Twisted Transport
138
139
Asynchronous transport for Twisted-based applications.
140
141
```python { .api }
142
from raven.transport.twisted import TwistedHTTPTransport
143
144
class TwistedHTTPTransport(AsyncTransport):
145
def __init__(self, parsed_url, timeout=5):
146
"""
147
Twisted-based async HTTP transport.
148
149
Parameters:
150
- parsed_url: Parsed Sentry DSN URL
151
- timeout (int): Request timeout in seconds
152
"""
153
```
154
155
### Tornado Transport
156
157
Asynchronous transport for Tornado applications.
158
159
```python { .api }
160
from raven.transport.tornado import TornadoHTTPTransport
161
162
class TornadoHTTPTransport(AsyncTransport):
163
def __init__(self, parsed_url, timeout=5):
164
"""
165
Tornado async HTTP transport.
166
167
Parameters:
168
- parsed_url: Parsed Sentry DSN URL
169
- timeout (int): Request timeout in seconds
170
"""
171
```
172
173
### Eventlet Transport
174
175
Asynchronous transport for eventlet-based applications.
176
177
```python { .api }
178
from raven.transport.eventlet import EventletHTTPTransport
179
180
class EventletHTTPTransport(AsyncTransport):
181
def __init__(self, parsed_url, timeout=5):
182
"""
183
Eventlet-based async HTTP transport.
184
185
Parameters:
186
- parsed_url: Parsed Sentry DSN URL
187
- timeout (int): Request timeout in seconds
188
"""
189
```
190
191
### Transport Registry
192
193
Management system for transport class registration and selection.
194
195
```python { .api }
196
from raven.transport.registry import TransportRegistry, default_transports
197
198
class TransportRegistry:
199
def __init__(self):
200
"""Transport registry for managing available transports."""
201
202
def register(self, scheme, transport_class):
203
"""
204
Register transport class for URL scheme.
205
206
Parameters:
207
- scheme (str): URL scheme (http, https, etc.)
208
- transport_class (type): Transport class
209
"""
210
211
def get_transport(self, parsed_url, **options):
212
"""
213
Get transport instance for URL.
214
215
Parameters:
216
- parsed_url: Parsed Sentry DSN URL
217
- **options: Transport configuration options
218
219
Returns:
220
Transport: Transport instance
221
"""
222
223
# Default transport registry with all available transports
224
default_transports = TransportRegistry()
225
```
226
227
## Usage Examples
228
229
### Custom Transport Configuration
230
231
```python
232
from raven import Client
233
from raven.transport.threaded import ThreadedHTTPTransport
234
235
# Use specific transport with custom settings
236
transport = ThreadedHTTPTransport(
237
timeout=10,
238
shutdown_timeout=2
239
)
240
241
client = Client(
242
dsn='https://your-dsn@sentry.io/project-id',
243
transport=transport
244
)
245
```
246
247
### Gevent Application
248
249
```python
250
import gevent
251
from raven import Client
252
from raven.transport.gevent import GeventedHTTPTransport
253
254
# Configure gevent-compatible client
255
client = Client(
256
dsn='https://your-dsn@sentry.io/project-id',
257
transport=GeventedHTTPTransport
258
)
259
260
def worker():
261
try:
262
# This won't block other greenlets
263
risky_operation()
264
except Exception:
265
client.captureException()
266
267
# Spawn multiple workers
268
jobs = [gevent.spawn(worker) for _ in range(10)]
269
gevent.joinall(jobs)
270
```
271
272
### Twisted Application
273
274
```python
275
from twisted.internet import reactor
276
from raven import Client
277
from raven.transport.twisted import TwistedHTTPTransport
278
279
client = Client(
280
dsn='https://your-dsn@sentry.io/project-id',
281
transport=TwistedHTTPTransport
282
)
283
284
def handle_error(failure):
285
client.captureException()
286
287
def async_operation():
288
d = some_async_call()
289
d.addErrback(handle_error)
290
return d
291
292
reactor.run()
293
```
294
295
### Tornado Application
296
297
```python
298
import tornado.web
299
import tornado.ioloop
300
from raven import Client
301
from raven.transport.tornado import TornadoHTTPTransport
302
303
class MainHandler(tornado.web.RequestHandler):
304
def initialize(self):
305
self.client = Client(
306
dsn='https://your-dsn@sentry.io/project-id',
307
transport=TornadoHTTPTransport
308
)
309
310
async def get(self):
311
try:
312
result = await async_database_call()
313
self.write(result)
314
except Exception:
315
self.client.captureException()
316
self.set_status(500)
317
self.write('Error occurred')
318
319
app = tornado.web.Application([
320
(r'/', MainHandler),
321
])
322
323
if __name__ == '__main__':
324
app.listen(8888)
325
tornado.ioloop.IOLoop.current().start()
326
```
327
328
### Custom Transport Implementation
329
330
```python
331
from raven.transport.base import Transport
332
import requests
333
334
class CustomHTTPTransport(Transport):
335
def __init__(self, parsed_url, timeout=5, retries=3):
336
super().__init__(parsed_url, timeout)
337
self.retries = retries
338
339
def send(self, data, headers):
340
url = f"{self.parsed_url.scheme}://{self.parsed_url.netloc}/api/{self.parsed_url.path.strip('/')}/store/"
341
342
for attempt in range(self.retries):
343
try:
344
response = requests.post(
345
url,
346
data=data,
347
headers=headers,
348
timeout=self.timeout
349
)
350
response.raise_for_status()
351
return response.headers.get('X-Sentry-ID')
352
353
except requests.RequestException as e:
354
if attempt == self.retries - 1:
355
raise
356
time.sleep(2 ** attempt) # Exponential backoff
357
358
# Register custom transport
359
from raven.transport.registry import default_transports
360
default_transports.register('https', CustomHTTPTransport)
361
362
client = Client('https://your-dsn@sentry.io/project-id')
363
```
364
365
### Transport Selection Based on Environment
366
367
```python
368
import os
369
from raven import Client
370
371
def get_transport_class():
372
if os.getenv('GEVENT_SUPPORT'):
373
from raven.transport.gevent import GeventedHTTPTransport
374
return GeventedHTTPTransport
375
elif os.getenv('TWISTED_SUPPORT'):
376
from raven.transport.twisted import TwistedHTTPTransport
377
return TwistedHTTPTransport
378
elif os.getenv('ASYNC_SUPPORT'):
379
from raven.transport.threaded import ThreadedHTTPTransport
380
return ThreadedHTTPTransport
381
else:
382
from raven.transport.http import HTTPTransport
383
return HTTPTransport
384
385
client = Client(
386
dsn=os.getenv('SENTRY_DSN'),
387
transport=get_transport_class()
388
)
389
```
390
391
### Error Handling in Transports
392
393
```python
394
from raven import Client
395
from raven.transport.threaded import ThreadedHTTPTransport
396
import logging
397
398
# Configure logging to see transport errors
399
logging.basicConfig(level=logging.DEBUG)
400
401
client = Client(
402
dsn='https://your-dsn@sentry.io/project-id',
403
transport=ThreadedHTTPTransport,
404
# Raise errors instead of swallowing them
405
raise_send_errors=True
406
)
407
408
try:
409
client.captureMessage('Test message')
410
except Exception as e:
411
print(f"Transport error: {e}")
412
```