This repository was archived by the owner on Oct 23, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathmodels.py
275 lines (221 loc) · 9.02 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""
raven.contrib.django.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Acts as an implicit hook for Django installs.
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# flake8: noqa
from __future__ import absolute_import, unicode_literals
import logging
import sys
import warnings
import django
from django.conf import settings
from django.core.signals import got_request_exception, request_started
from threading import Lock
from raven.utils.conf import convert_options
from raven.utils.compat import PY2, binary_type, text_type
from raven.utils.imports import import_string
logger = logging.getLogger('sentry.errors.client')
def get_installed_apps():
"""
Modules in settings.INSTALLED_APPS as a set.
"""
return set(settings.INSTALLED_APPS)
_client = (None, None)
class ProxyClient(object):
"""
A proxy which represents the currently client at all times.
"""
# introspection support:
__members__ = property(lambda x: x.__dir__())
# Need to pretend to be the wrapped class, for the sake of objects that care
# about this (especially in equality tests)
__class__ = property(lambda x: get_client().__class__)
__dict__ = property(lambda o: get_client().__dict__)
__repr__ = lambda x: repr(get_client())
__getattr__ = lambda x, o: getattr(get_client(), o)
__setattr__ = lambda x, o, v: setattr(get_client(), o, v)
__delattr__ = lambda x, o: delattr(get_client(), o)
__lt__ = lambda x, o: get_client() < o
__le__ = lambda x, o: get_client() <= o
__eq__ = lambda x, o: get_client() == o
__ne__ = lambda x, o: get_client() != o
__gt__ = lambda x, o: get_client() > o
__ge__ = lambda x, o: get_client() >= o
if PY2:
__cmp__ = lambda x, o: cmp(get_client(), o) # NOQA
__hash__ = lambda x: hash(get_client())
# attributes are currently not callable
# __call__ = lambda x, *a, **kw: get_client()(*a, **kw)
__nonzero__ = lambda x: bool(get_client())
__len__ = lambda x: len(get_client())
__getitem__ = lambda x, i: get_client()[i]
__iter__ = lambda x: iter(get_client())
__contains__ = lambda x, i: i in get_client()
__getslice__ = lambda x, i, j: get_client()[i:j]
__add__ = lambda x, o: get_client() + o
__sub__ = lambda x, o: get_client() - o
__mul__ = lambda x, o: get_client() * o
__floordiv__ = lambda x, o: get_client() // o
__mod__ = lambda x, o: get_client() % o
__divmod__ = lambda x, o: get_client().__divmod__(o)
__pow__ = lambda x, o: get_client() ** o
__lshift__ = lambda x, o: get_client() << o
__rshift__ = lambda x, o: get_client() >> o
__and__ = lambda x, o: get_client() & o
__xor__ = lambda x, o: get_client() ^ o
__or__ = lambda x, o: get_client() | o
__div__ = lambda x, o: get_client().__div__(o)
__truediv__ = lambda x, o: get_client().__truediv__(o)
__neg__ = lambda x: -(get_client())
__pos__ = lambda x: +(get_client())
__abs__ = lambda x: abs(get_client())
__invert__ = lambda x: ~(get_client())
__complex__ = lambda x: complex(get_client())
__int__ = lambda x: int(get_client())
if PY2:
__long__ = lambda x: long(get_client()) # NOQA
__float__ = lambda x: float(get_client())
__str__ = lambda x: binary_type(get_client())
__unicode__ = lambda x: text_type(get_client())
__oct__ = lambda x: oct(get_client())
__hex__ = lambda x: hex(get_client())
__index__ = lambda x: get_client().__index__()
__coerce__ = lambda x, o: x.__coerce__(x, o)
__enter__ = lambda x: x.__enter__()
__exit__ = lambda x, *a, **kw: x.__exit__(*a, **kw)
client = ProxyClient()
def get_client(client=None, reset=False):
global _client
tmp_client = client is not None
if not tmp_client:
client = getattr(settings, 'SENTRY_CLIENT', 'raven.contrib.django.DjangoClient')
if _client[0] != client or reset:
options = convert_options(
settings,
defaults={
'include_paths': get_installed_apps(),
},
)
try:
Client = import_string(client)
except ImportError:
logger.exception('Failed to import client: %s', client)
if not _client[1]:
# If there is no previous client, set the default one.
client = 'raven.contrib.django.DjangoClient'
_client = (client, get_client(client))
else:
instance = Client(**options)
if not tmp_client:
_client = (client, instance)
return instance
return _client[1]
def sentry_exception_handler(request=None, **kwargs):
try:
client.captureException(exc_info=sys.exc_info(), request=request)
except Exception as exc:
try:
logger.exception('Unable to process log entry: %s' % (exc,))
except Exception as exc:
warnings.warn('Unable to process log entry: %s' % (exc,))
class SentryDjangoHandler(object):
def __init__(self, client=client):
self.client = client
try:
import celery
except ImportError:
self.has_celery = False
else:
self.has_celery = celery.VERSION >= (2, 5)
self.celery_handler = None
def install_celery(self):
from raven.contrib.celery import (
SentryCeleryHandler, register_logger_signal
)
ignore_expected = getattr(settings,
'SENTRY_CELERY_IGNORE_EXPECTED',
False)
self.celery_handler = SentryCeleryHandler(client,
ignore_expected=ignore_expected)\
.install()
loglevel = (
getattr(settings, 'RAVEN_CONFIG', {}).get('CELERY_LOGLEVEL')
or getattr(settings, 'SENTRY_CELERY_LOGLEVEL', None)
)
if loglevel is not None:
register_logger_signal(client, loglevel=loglevel)
def install(self):
request_started.connect(self.before_request, weak=False)
got_request_exception.connect(self.exception_handler, weak=False)
if self.has_celery:
try:
self.install_celery()
except Exception:
logger.exception('Failed to install Celery error handler')
def uninstall(self):
request_started.disconnect(self.before_request)
got_request_exception.disconnect(self.exception_handler)
if self.celery_handler:
self.celery_handler.uninstall()
def exception_handler(self, request=None, **kwargs):
try:
self.client.captureException(exc_info=sys.exc_info(), request=request)
except Exception as exc:
try:
logger.exception('Unable to process log entry: %s' % (exc,))
except Exception as exc:
warnings.warn('Unable to process log entry: %s' % (exc,))
def before_request(self, *args, **kwargs):
self.client.context.activate()
def register_serializers():
# force import so serializers can call register
import raven.contrib.django.serializers # NOQA
def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
else 'MIDDLEWARE_CLASSES'
# make sure to get an empty tuple when attr is None
middleware = getattr(settings, middleware_attr, ()) or ()
if set(lookup_names).isdisjoint(set(middleware)):
setattr(settings,
middleware_attr,
type(middleware)((middleware_name,)) + middleware)
_setup_lock = Lock()
_initialized = False
def initialize():
global _initialized
with _setup_lock:
if _initialized:
return
# mark this as initialized immediatley to avoid recursive import issues
_initialized = True
try:
register_serializers()
install_middleware(
'raven.contrib.django.middleware.SentryMiddleware',
(
'raven.contrib.django.middleware.SentryMiddleware',
'raven.contrib.django.middleware.SentryLogMiddleware'))
install_middleware(
'raven.contrib.django.middleware.DjangoRestFrameworkCompatMiddleware')
# XXX(dcramer): maybe this setting should disable ALL of this?
if not getattr(settings, 'DISABLE_SENTRY_INSTRUMENTATION', False):
handler = SentryDjangoHandler()
handler.install()
# instantiate client so hooks get registered
get_client() # NOQA
except Exception:
_initialized = False
# Django 1.7 uses ``raven.contrib.django.apps.RavenConfig``
if django.VERSION < (1, 7, 0):
initialize()