Skip to content

Commit

Permalink
Django: Save an extra (potential) DB lookup if SENTRY_SITE is set by …
Browse files Browse the repository at this point in the history
…not looking up django.contrib.sites. Catch any errors looking up the django.contrib.sites model, falling back to settings.SITE_ID.
  • Loading branch information
rcoup committed Feb 8, 2013
1 parent bdcb353 commit fa3b1c8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
14 changes: 9 additions & 5 deletions raven/contrib/django/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,15 @@ def build_msg(self, *args, **kwargs):
if frame.get('module', '').startswith('django.'):
frame['in_app'] = False

if 'django.contrib.sites' in settings.INSTALLED_APPS:
from django.contrib.sites import models as site_models
site = site_models.Site.objects.get_current()
site_name = site.name or site.domain
data['tags'].setdefault('site', site_name)
if (not self.site) and 'django.contrib.sites' in settings.INSTALLED_APPS:
try:
from django.contrib.sites import models as site_models
site = site_models.Site.objects.get_current()
site_name = site.name or site.domain
data['tags'].setdefault('site', site_name)
except:
# Database error? Fallback to the id
data['tags'].setdefault('site', settings.SITE_ID)

return data

Expand Down
22 changes: 22 additions & 0 deletions tests/contrib/django/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,28 @@ def test_adds_site_to_tags(self):
assert 'site' in event['tags']
assert tags['site'] == u'example.com'

def test_adds_site_to_tags_fallback(self):
with Settings(SITE_ID=12345): # nonexistant site, should fallback to SITE_ID
self.assertRaises(TemplateSyntaxError, self.client.get, reverse('sentry-template-exc'))

self.assertEquals(len(self.raven.events), 1)
event = self.raven.events.pop(0)

tags = event['tags']
assert 'site' in event['tags']
assert tags['site'] == 12345

def test_settings_site_overrides_contrib(self):
self.raven.site = 'FOO'
self.assertRaises(TemplateSyntaxError, self.client.get, reverse('sentry-template-exc'))

self.assertEquals(len(self.raven.events), 1)
event = self.raven.events.pop(0)

tags = event['tags']
assert 'site' in event['tags']
assert tags['site'] == 'FOO'


class DjangoTemplateTagTest(TestCase):
@mock.patch('raven.contrib.django.DjangoClient.get_public_dsn')
Expand Down

0 comments on commit fa3b1c8

Please sign in to comment.