Skip to content

Commit

Permalink
lots of changes for Django 1.4 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
dcramer committed Sep 3, 2012
1 parent c0eb5d7 commit ba5178c
Show file tree
Hide file tree
Showing 30 changed files with 155 additions and 132 deletions.
6 changes: 5 additions & 1 deletion runtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@
import logging
import os
import sys
import warnings
from os.path import dirname, abspath
from optparse import OptionParser

sys.path.insert(0, dirname(abspath(__file__)))

logging.getLogger('sentry').addHandler(logging.StreamHandler())
logging.basicConfig(level=logging.DEBUG)

# Force all warnings in Django or Sentry to throw exceptions
warnings.filterwarnings('error', '', RuntimeWarning, module=r'^(sentry|django).*')

from django.conf import settings

Expand Down
5 changes: 2 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,13 @@
'django-paging>=0.2.4',
'django-picklefield>=0.2.0',
'django-templatetag-sugar>=0.1.0',
'gunicorn>=0.13.4',
'gunicorn>=0.14.0',
'logan>=0.3.1',
'pynliner>=0.4.0',
'python-dateutil>=1.5.0,<2.0.0',
'pytz>=2011n',
'raven>=2.0.3',
'simplejson>=2.1.6',
'South>=0.7',
'South>=0.7.6',
'httpagentparser>=1.0.5',
'django-social-auth>=0.7.1,<1.0',
]
Expand Down
22 changes: 16 additions & 6 deletions src/sentry/conf/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,15 @@

APPEND_SLASH = True

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir))

sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, '..')))
sys.path.insert(0, os.path.normpath(os.path.join(PROJECT_ROOT, os.pardir)))

CACHE_BACKEND = 'locmem:///'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}

DATABASES = {
'default': {
Expand Down Expand Up @@ -89,7 +93,7 @@
# calendars according to the current locale
USE_L10N = True

USE_TZ = False
USE_TZ = True

# Make this unique, and don't share it with anybody.
SECRET_KEY = hashlib.md5(socket.gethostname() + ')*)&8a36)6%74e@-ne5(-!8a(vv#tkv)(eyg&@0=zd^pl!7=y@').hexdigest()
Expand Down Expand Up @@ -152,7 +156,11 @@
'south',
)

ADMIN_MEDIA_PREFIX = '/_admin_media/'
STATIC_URL = '/_admin_media/'

LOCALE_PATHS = (
os.path.join(PROJECT_ROOT, 'locale'),
)

# Auth configuration

Expand Down Expand Up @@ -220,7 +228,6 @@
CELERY_RESULT_BACKEND = None
CELERY_TASK_RESULT_EXPIRES = 1


# Sentry and Raven configuration

SENTRY_PUBLIC = False
Expand All @@ -229,6 +236,9 @@

EMAIL_SUBJECT_PREFIX = '[Sentry] '

# Disable South in tests as it is sending incorrect create signals
SOUTH_TESTS_MIGRATE = False

# Configure logging
from raven.conf import setup_logging
from raven.contrib.django.handlers import SentryHandler
Expand Down
17 changes: 13 additions & 4 deletions src/sentry/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
import re
import warnings

from django.conf import settings as dj_settings
from django.core.signals import request_finished
from django.db import models, transaction, IntegrityError
from django.db.models import Sum
from django.db.models.expressions import F, ExpressionNode
from django.db.models.signals import post_save, post_delete, post_init, class_prepared
from django.utils import timezone
from django.utils.encoding import force_unicode, smart_str

from raven.utils.encoding import to_string
Expand All @@ -30,7 +32,7 @@
from sentry.signals import regression_signal
from sentry.tasks.index import index_event
from sentry.utils.cache import cache, Lock
from sentry.utils.dates import utc_to_local, get_sql_date_trunc
from sentry.utils.dates import get_sql_date_trunc
from sentry.utils.db import get_db_engine, has_charts, resolve_expression_node
from sentry.utils.queue import maybe_delay

Expand Down Expand Up @@ -318,7 +320,7 @@ def _get_chart_data(self, queryset, max_days=90, db='default'):
if not has_charts(db):
return []

today = datetime.datetime.now().replace(microsecond=0, second=0, minute=0)
today = timezone.now().replace(microsecond=0, second=0, minute=0)
min_date = today - datetime.timedelta(days=max_days)

if max_days > 30:
Expand Down Expand Up @@ -402,7 +404,7 @@ def from_kwargs(self, project, **kwargs):
logger_name = kwargs.pop('logger', None) or settings.DEFAULT_LOGGER_NAME
server_name = kwargs.pop('server_name', None)
site = kwargs.pop('site', None)
date = kwargs.pop('timestamp', None) or datetime.datetime.utcnow()
date = kwargs.pop('timestamp', None) or timezone.now()
checksum = kwargs.pop('checksum', None)
tags = kwargs.pop('tags', [])

Expand All @@ -412,7 +414,14 @@ def from_kwargs(self, project, **kwargs):

# We must convert date to local time so Django doesn't mess it up
# based on TIME_ZONE
date = utc_to_local(date)
if dj_settings.TIME_ZONE:
if not timezone.is_aware(date):
date = date.replace(tzinfo=timezone.utc)
elif timezone.is_aware(date):
date = date.replace(tzinfo=None)

print date

data = kwargs

kwargs = {
Expand Down
27 changes: 13 additions & 14 deletions src/sentry/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import uuid
import urlparse

from datetime import datetime
from hashlib import md5
from indexer.models import BaseIndex
from picklefield.fields import PickledObjectField
Expand All @@ -26,9 +25,9 @@
from django.db.models.signals import post_syncdb, post_save, pre_delete, \
class_prepared
from django.template.defaultfilters import slugify
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.encoding import smart_unicode
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _

from sentry.conf import settings
Expand Down Expand Up @@ -112,7 +111,7 @@ class TeamMember(Model):
user = models.ForeignKey(User, related_name="sentry_teammember_set")
is_active = models.BooleanField(default=True)
type = models.IntegerField(choices=MEMBER_TYPES, default=globals().get(settings.DEFAULT_PROJECT_ACCESS))
date_added = models.DateTimeField(default=now)
date_added = models.DateTimeField(default=timezone.now)

objects = BaseManager()

Expand All @@ -136,7 +135,7 @@ class Project(Model):
owner = models.ForeignKey(User, related_name="sentry_owned_project_set", null=True)
team = models.ForeignKey(Team, null=True)
public = models.BooleanField(default=settings.ALLOW_PUBLIC_PROJECTS)
date_added = models.DateTimeField(default=now)
date_added = models.DateTimeField(default=timezone.now)
status = models.PositiveIntegerField(default=0, choices=(
(0, 'Visible'),
(1, 'Hidden'),
Expand Down Expand Up @@ -289,7 +288,7 @@ class PendingTeamMember(Model):
team = models.ForeignKey(Team, related_name="pending_member_set")
email = models.EmailField()
type = models.IntegerField(choices=MEMBER_TYPES, default=globals().get(settings.DEFAULT_PROJECT_ACCESS))
date_added = models.DateTimeField(default=now)
date_added = models.DateTimeField(default=timezone.now)

objects = BaseManager()

Expand Down Expand Up @@ -391,8 +390,8 @@ class Group(MessageBase):
"""
status = models.PositiveIntegerField(default=0, choices=STATUS_LEVELS, db_index=True)
times_seen = models.PositiveIntegerField(default=1, db_index=True)
last_seen = models.DateTimeField(default=now, db_index=True)
first_seen = models.DateTimeField(default=now, db_index=True)
last_seen = models.DateTimeField(default=timezone.now, db_index=True)
first_seen = models.DateTimeField(default=timezone.now, db_index=True)
resolved_at = models.DateTimeField(null=True, db_index=True)
# active_at should be the same as first_seen by default
active_at = models.DateTimeField(null=True, db_index=True)
Expand All @@ -418,7 +417,7 @@ def __unicode__(self):

def save(self, *args, **kwargs):
if not self.last_seen:
self.last_seen = datetime.now()
self.last_seen = timezone.now()
if not self.first_seen:
self.first_seen = self.last_seen
if not self.active_at:
Expand Down Expand Up @@ -482,7 +481,7 @@ class Event(MessageBase):
"""
group = models.ForeignKey(Group, blank=True, null=True, related_name="event_set")
event_id = models.CharField(max_length=32, null=True, db_column="message_id")
datetime = models.DateTimeField(default=now, db_index=True)
datetime = models.DateTimeField(default=timezone.now, db_index=True)
time_spent = models.FloatField(null=True)
server_name = models.CharField(max_length=128, db_index=True, null=True)
site = models.CharField(max_length=128, db_index=True, null=True)
Expand Down Expand Up @@ -627,8 +626,8 @@ class MessageFilterValue(Model):
times_seen = models.PositiveIntegerField(default=0)
key = models.CharField(choices=FILTER_KEYS, max_length=32)
value = models.CharField(max_length=200)
last_seen = models.DateTimeField(default=now, db_index=True, null=True)
first_seen = models.DateTimeField(default=now, db_index=True, null=True)
last_seen = models.DateTimeField(default=timezone.now, db_index=True, null=True)
first_seen = models.DateTimeField(default=timezone.now, db_index=True, null=True)

objects = BaseManager()

Expand Down Expand Up @@ -692,8 +691,8 @@ class SearchDocument(Model):
group = models.ForeignKey(Group)
total_events = models.PositiveIntegerField(default=1)
status = models.PositiveIntegerField(default=0)
date_added = models.DateTimeField(default=now)
date_changed = models.DateTimeField(default=now)
date_added = models.DateTimeField(default=timezone.now)
date_changed = models.DateTimeField(default=timezone.now)

objects = SearchDocumentManager()

Expand Down Expand Up @@ -907,4 +906,4 @@ def set_language_on_logon(request, user, **kwargs):
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^social_auth\.fields\.JSONField"])
except:
pass
pass
2 changes: 1 addition & 1 deletion src/sentry/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
:license: BSD, see LICENSE for more details.
"""

from sentry.plugins.base import *
from sentry.plugins.base import * # NOQA
2 changes: 1 addition & 1 deletion src/sentry/plugins/bases/issue.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_auth_for_user(self, user, **kwargs):
"""
assert self.auth_provider, 'There is no auth provider configured for this plugin.'

if user.is_authenticated():
if not user.is_authenticated():
return None

try:
Expand Down
2 changes: 1 addition & 1 deletion src/sentry/processors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
:license: BSD, see LICENSE for more details.
"""

from sentry.processors.base import *
from sentry.processors.base import * # NOQA
15 changes: 5 additions & 10 deletions src/sentry/services/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,15 @@

from gunicorn import arbiter
from gunicorn.app import djangoapp
import gunicorn.util

from sentry.services.base import Service


if gunicorn.version_info < (0, 14, 0):
def _setup_app(app):
app.validate()
app.activate_translation()
else:
def _setup_app(app):
import gunicorn.util
djangoapp.make_default_env(app.cfg)
djwsgi = gunicorn.util.import_module("gunicorn.app.django_wsgi")
djwsgi.make_wsgi_application()
def _setup_app(app):
djangoapp.make_default_env(app.cfg)
djwsgi = gunicorn.util.import_module("gunicorn.app.django_wsgi")
djwsgi.make_wsgi_application()


class SentryApplication(djangoapp.DjangoApplication):
Expand Down
6 changes: 3 additions & 3 deletions src/sentry/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
:license: BSD, see LICENSE for more details.
"""

import sentry.tasks.cleanup
import sentry.tasks.index
import sentry.tasks.store
import sentry.tasks.cleanup # NOQA
import sentry.tasks.index # NOQA
import sentry.tasks.store # NOQA
3 changes: 2 additions & 1 deletion src/sentry/tasks/cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def cleanup(days=30, logger=None, site=None, server=None, level=None,
"""
import datetime

from django.utils import timezone
from sentry.models import Group, Event, MessageCountByMinute, \
MessageFilterValue, FilterValue, SearchDocument, ProjectCountByMinute
from sentry.utils.query import RangeQuerySetWrapper, SkinnyQuerySet
Expand All @@ -49,7 +50,7 @@ def cleanup_groups(iterable):
# TODO: we should collect which messages above were deleted
# and potentially just send out post_delete signals where
# GroupedMessage can update itself accordingly
ts = datetime.datetime.utcnow() - datetime.timedelta(days=days)
ts = timezone.now() - datetime.timedelta(days=days)

# Message
qs = SkinnyQuerySet(Event).filter(datetime__lte=ts)
Expand Down
3 changes: 2 additions & 1 deletion src/sentry/templatetags/sentry_admin_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from django import template
from django.db.models import Sum
from django.utils import timezone

register = template.Library()

Expand All @@ -18,7 +19,7 @@ def with_event_counts(project_list):
from sentry.models import ProjectCountByMinute
results = dict(ProjectCountByMinute.objects.filter(
project__in=project_list,
date__gte=datetime.datetime.now() - datetime.timedelta(days=30),
date__gte=timezone.now() - datetime.timedelta(days=30),
).values_list('project').annotate(
total_events=Sum('times_seen'),
).values_list('project', 'total_events'))
Expand Down
12 changes: 8 additions & 4 deletions src/sentry/templatetags/sentry_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from paging.helpers import paginate as paginate_func
from sentry.conf import settings
from sentry.utils import json
from sentry.utils.dates import utc_to_local, local_to_utc
from templatetag_sugar.register import tag
from templatetag_sugar.parser import Name, Variable, Constant, Optional

Expand Down Expand Up @@ -134,9 +133,11 @@ def sentry_version():


@register.filter
def timesince(value):
def timesince(value, now=None):
from django.template.defaultfilters import timesince
now = utc_to_local(datetime.datetime.utcnow())
from django.utils import timezone
if now is None:
now = timezone.now()
if not value:
return _('never')
if value < (now - datetime.timedelta(days=5)):
Expand Down Expand Up @@ -266,7 +267,10 @@ def as_bookmarks(group_list, user):
@register.filter
def date(datetime, arg=None):
from django.template.defaultfilters import date
return date(local_to_utc(datetime), arg)
from django.utils import timezone
if not timezone.is_aware(datetime):
datetime = datetime.replace(tzinfo=timezone.utc)
return date(datetime, arg)


@tag(register, [Constant('for'), Variable('user'),
Expand Down
5 changes: 2 additions & 3 deletions src/sentry/utils/cache.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import django
import logging
import time

from django.core.cache import get_cache, cache

from sentry.conf import settings

if django.VERSION > (1, 2) and settings.CACHE_BACKEND != 'default':
cache = get_cache(settings.CACHE_BACKEND)
if settings.CACHE_BACKEND != 'default':
cache = get_cache(settings.CACHE_BACKEND) # NOQA

_cache = cache

Expand Down
Loading

0 comments on commit ba5178c

Please sign in to comment.