|
| 1 | +from __future__ import absolute_import |
| 2 | + |
| 3 | +from threading import Lock |
| 4 | + |
| 5 | +from django.core import signals |
| 6 | + |
| 7 | +try: |
| 8 | + from django.urls import resolve |
| 9 | +except ImportError: |
| 10 | + from django.core.urlresolvers import resolve |
| 11 | + |
| 12 | +from sentry_sdk import get_current_hub, configure_scope, capture_exception |
| 13 | +from sentry_sdk.hub import _internal_exceptions |
| 14 | +from ._wsgi import RequestExtractor |
| 15 | + |
| 16 | + |
| 17 | +class DjangoRequestExtractor(RequestExtractor): |
| 18 | + @property |
| 19 | + def url(self): |
| 20 | + return self.request.build_absolute_uri(self.request.path) |
| 21 | + |
| 22 | + @property |
| 23 | + def env(self): |
| 24 | + return self.request.META |
| 25 | + |
| 26 | + @property |
| 27 | + def cookies(self): |
| 28 | + return self.request.COOKIES |
| 29 | + |
| 30 | + @property |
| 31 | + def raw_data(self): |
| 32 | + return self.request.body |
| 33 | + |
| 34 | + @property |
| 35 | + def form(self): |
| 36 | + return self.request.POST |
| 37 | + |
| 38 | + @property |
| 39 | + def files(self): |
| 40 | + return self.request.FILES |
| 41 | + |
| 42 | + def size_of_file(self, file): |
| 43 | + return file.size |
| 44 | + |
| 45 | + |
| 46 | +_installer_lock = Lock() |
| 47 | +_installed = False |
| 48 | + |
| 49 | + |
| 50 | +def install(client): |
| 51 | + global _installed |
| 52 | + with _installer_lock: |
| 53 | + if _installed: |
| 54 | + return |
| 55 | + |
| 56 | + _install_impl() |
| 57 | + _installed = True |
| 58 | + |
| 59 | + |
| 60 | +def _install_impl(): |
| 61 | + from django.core.handlers.base import BaseHandler |
| 62 | + |
| 63 | + old_get_response = BaseHandler.get_response |
| 64 | + |
| 65 | + def sentry_patched_get_response(self, request): |
| 66 | + with get_current_hub().push_scope(): |
| 67 | + get_current_hub().add_event_processor( |
| 68 | + lambda: _make_event_processor(request) |
| 69 | + ) |
| 70 | + |
| 71 | + with configure_scope() as scope: |
| 72 | + scope.transaction = resolve(request.path).func.__name__ |
| 73 | + |
| 74 | + return old_get_response(self, request) |
| 75 | + |
| 76 | + BaseHandler.get_response = sentry_patched_get_response |
| 77 | + |
| 78 | + signals.got_request_exception.connect(_got_request_exception) |
| 79 | + |
| 80 | + |
| 81 | +def _make_event_processor(request): |
| 82 | + def processor(event): |
| 83 | + with _internal_exceptions(): |
| 84 | + DjangoRequestExtractor(request).extract_into_event(event) |
| 85 | + |
| 86 | + # TODO: user info |
| 87 | + |
| 88 | + return processor |
| 89 | + |
| 90 | + |
| 91 | +def _got_request_exception(request=None, **kwargs): |
| 92 | + capture_exception() |
0 commit comments