Permalink
Browse files

First draft of Django 1.5 logging configuration.

Django 1.5 compatibility: model field definitions and arguments.

Django 1.5 compatibility: Small typo in log settings.

Django 1.5 compatibility: Stop importing log_settings since we don't use it anymore.

Django 1.5 compatibility: Fix JSON field.

Django compatibility: More model field definitions that got left out of last commit.

Django compatibility: The big one.

Django compatibility: more sumo cleanup.
  • Loading branch information...
1 parent 9693034 commit 312a88e86a7469c1a99fb81ebf694fb4faad044b @ubernostrum ubernostrum committed with groovecoder Feb 1, 2013
@@ -37,7 +37,7 @@ def contribute_to_class(self, cls, name):
t = ActionCounterCreator(self)
setattr(cls, name, t)
- def get_db_prep_save(self, value):
+ def get_db_prep_save(self, value, connection):
pass
View
@@ -379,7 +379,7 @@ class Submission(models.Model):
_("Hide this demo from others?"), default=False)
censored = models.BooleanField()
censored_url = models.URLField(
- _("Redirect URL for censorship"),
+ _("Redirect URL for censorship."),
verify_exists=False, blank=True, null=True)
navbar_optout = models.BooleanField(
@@ -430,7 +430,7 @@ class Submission(models.Model):
video_url = VideoEmbedURLField(
_("have a video of your demo in action? (optional)"),
- verify_exists=False, blank=True, null=True)
+ blank=True, null=True)
demo_package = ReplacingZipFileField(
_('select a ZIP file containing your demo'),
@@ -442,7 +442,7 @@ class Submission(models.Model):
source_code_url = models.URLField(
_("Is your source code also available somewhere else on the web (e.g., github)? Please share the link."),
- verify_exists=False, blank=True, null=True)
+ blank=True, null=True)
license_name = models.CharField(
_("Select the license that applies to your source code."),
max_length=64, blank=False,
View
@@ -106,7 +106,7 @@ class Meta:
locale = LocaleField(null=True, blank=True, db_index=True,
verbose_name=_(u'Language'))
homepage = models.URLField(max_length=255, blank=True, default='',
- verify_exists=False, error_messages={
+ error_messages={
'invalid': _(u'This URL has an invalid format. '
u'Valid URLs look like '
u'http://example.com/my_page.')})
@@ -649,12 +649,12 @@ class Event(ModelBase):
date = models.DateField()
end_date = models.DateField(blank=True, null=True)
conference = models.CharField(max_length=255)
- conference_link = models.URLField(blank=True, verify_exists=False)
+ conference_link = models.URLField(blank=True)
location = models.CharField(max_length=255)
people = models.TextField()
description = models.TextField()
done = models.BooleanField(default=False)
- materials = models.URLField(blank=True, verify_exists=False)
+ materials = models.URLField(blank=True)
calendar = models.ForeignKey(Calendar)
class Meta:
@@ -111,29 +111,6 @@ def test_devmo_url(self):
req.locale = 'zh-TW'
eq_(devmo_url(context, localized_page), '/zh_tw/HTML')
- def test_devmo_url_mindtouch_disabled(self):
- _old = settings.DEKIWIKI_ENDPOINT
- settings.DEKIWIKI_ENDPOINT = False
-
- localized_page = 'article-title'
- req = test_utils.RequestFactory().get('/')
- context = {'request': req}
-
- req.locale = 'fr'
- eq_(devmo_url(context, localized_page), '/fr/docs/le-title')
-
- settings.DEKIWIKI_ENDPOINT = _old
-
- def test_devmo_url_mindtouch_disabled_redirect(self):
- # Skipping this test for now, redirect model logic is coupled to view
- raise SkipTest()
- _old = settings.DEKIWIKI_ENDPOINT
- settings.DEKIWIKI_ENDPOINT = False
-
- # TODO: add redirect localized pages to fixture and test
-
- settings.DEKIWIKI_ENDPOINT = _old
-
class TestDevMoUrlResolvers(test_utils.TestCase):
def test_prefixer_get_language(self):
View
@@ -2,6 +2,7 @@
import re
import urllib
+from django.core import urlresolvers
from django.http import HttpResponsePermanentRedirect, HttpResponseForbidden
from django.middleware import common
from django.utils.encoding import iri_to_uri, smart_str, smart_unicode
@@ -128,6 +129,15 @@ def process_exception(self, request, exception):
return jingo.render(request, 'sumo/read-only.html', status=503)
+def is_valid_path(request, path):
+ urlconf = getattr(request, 'urlconf', None)
+ try:
+ urlresolvers.resolve(path, urlconf)
+ return True
+ except urlresolvers.Resolver404:
+ return False
+
+
class RemoveSlashMiddleware(object):
"""
Middleware that tries to remove a trailing slash if there was a 404.
@@ -139,8 +149,8 @@ class RemoveSlashMiddleware(object):
def process_response(self, request, response):
if (response.status_code == 404
and request.path_info.endswith('/')
- and not common._is_valid_path(request.path_info)
- and common._is_valid_path(request.path_info[:-1])):
+ and not is_valid_path(request, request.path_info)
+ and is_valid_path(request, request.path_info[:-1])):
# Use request.path because we munged app/locale in path_info.
newurl = request.path[:-1]
if request.GET:
@@ -37,7 +37,7 @@ def tearDown(self):
models.signals.pre_delete.disconnect(self.db_error)
def db_error(self, *args, **kwargs):
- raise mysql.OperationalError("You can't do this in read-only mode.")
+ raise DatabaseError("You can't do this in read-only mode.")
def test_db_error(self):
assert_raises(DatabaseError, Question.objects.create, id=12)
@@ -41,13 +41,13 @@ def setUp(self):
@raises(KeyError)
def test_no_dir_attribute(self):
"""Make sure dir attr isn't rendered when no dir is specified."""
- html = jingo.render_to_string(self.request, self.template)
+ html = jingo.render_to_string(self.request.get('/'), self.template)
doc = pq(html)
doc('html')[0].attrib['dir']
def test_rtl_dir_attribute(self):
"""Make sure dir attr is set to 'rtl' when specified as so."""
- html = jingo.render_to_string(self.request, self.template,
+ html = jingo.render_to_string(self.request.get('/'), self.template,
{'dir': 'rtl'})
doc = pq(html)
dir_attr = doc('html').attr['dir']
@@ -59,15 +59,15 @@ def test_multi_feeds(self):
feed_urls = (('/feed_one', 'First Feed'),
('/feed_two', 'Second Feed'),)
- doc = pq(jingo.render_to_string(self.request, self.template,
+ doc = pq(jingo.render_to_string(self.request.get('/'), self.template,
{'feeds': feed_urls}))
feeds = doc('link[type="application/atom+xml"]')
eq_(2, len(feeds))
eq_('First Feed', feeds[0].attrib['title'])
eq_('Second Feed', feeds[1].attrib['title'])
def test_readonly_attr(self):
- html = jingo.render_to_string(self.request, self.template)
+ html = jingo.render_to_string(self.request.get('/'), self.template)
doc = pq(html)
eq_('false', doc('body')[0].attrib['data-readonly'])
@@ -89,7 +89,7 @@ def non_field_errors(self):
source = ("""{% from "layout/errorlist.html" import errorlist %}"""
"""{{ errorlist(form) }}""")
- html = jingo.render_to_string(self.request,
+ html = jingo.render_to_string(self.request.get('/'),
jingo.env.from_string(source),
{'form': MockForm()})
assert '<"evil&ness' not in html
@@ -1,7 +1,7 @@
import threading
from django.conf import settings
-from django.core.handlers.wsgi import WSGIRequest
+from django.test.client import RequestFactory
from django.core.urlresolvers import reverse as django_reverse
from django.utils.translation.trans_real import parse_accept_lang_header
@@ -100,7 +100,7 @@ def split_path(path):
class Prefixer(object):
def __init__(self, request=None, locale=None):
"""If request is omitted, fall back to a default locale."""
- self.request = request or WSGIRequest({'REQUEST_METHOD': 'bogus'})
+ self.request = request or RequestFactory(REQUEST_METHOD='bogus').request()
self.locale, self.shortened_path = split_path(self.request.path_info)
if locale:
self.locale = locale
View
@@ -1,41 +1,36 @@
import hashlib
-import os
-from django.contrib.auth import models as auth_models
-from django.contrib.auth.backends import ModelBackend
+from django.contrib.auth.hashers import BasePasswordHasher
+from django.contrib.auth.hashers import mask_hash
+from django.utils.crypto import constant_time_compare
+from django.utils.datastructures import SortedDict
-# http://fredericiana.com/2010/10/12/adding-support-for-stronger-password-hashes-to-django/
-"""
-from future import django_sha256_support
-
-Monkey-patch SHA-256 support into Django's auth system. If Django ticket #5600
-ever gets fixed, this can be removed.
-"""
-
-
-def get_hexdigest(algorithm, salt, raw_password):
- """Generate SHA-256 hash."""
- if algorithm == 'sha256':
- return hashlib.sha256((salt + raw_password).encode('utf8')).hexdigest()
- else:
- return get_hexdigest_old(algorithm, salt, raw_password)
-get_hexdigest_old = auth_models.get_hexdigest
-auth_models.get_hexdigest = get_hexdigest
-
-
-def set_password(self, raw_password):
- """Set SHA-256 password."""
- algo = 'sha256'
- salt = os.urandom(5).encode('hex') # Random, 10-digit (hex) salt.
- hsh = get_hexdigest(algo, salt, raw_password)
- self.password = '$'.join((algo, salt, hsh))
-auth_models.User.set_password = set_password
-
-
-class Sha256Backend(ModelBackend):
+class Sha256Hasher(BasePasswordHasher):
"""
- Overriding the Django model backend without changes ensures our
- monkeypatching happens by the time we import auth.
+ SHA-256 password hasher.
+
"""
- pass
+ algorithm = 'sha256'
+ digest = hashlib.sha256
+
+ def encode(self, password, salt):
+ assert password
+ assert salt and '$' not in salt
+ hash = self.digest(salt + password).hexdigest()
+ return "%s$%s$%s" % (self.algorithm, salt, hash)
+
+ def verify(self, password, encoded):
+ algorithm, salt, hash = encoded.split('$', 2)
+ assert algorithm == self.algorithm
+ encoded_2 = self.encode(password, salt)
+ return constant_time_compare(encoded, encoded_2)
+
+ def safe_summary(self, encoded):
+ algorithm, salt, hash = encoded.split('$', 2)
+ assert algorithm == self.algorithm
+ return SortedDict([
+ (_('algorithm'), algorithm),
+ (_('salt'), mask_hash(salt, show=2)),
+ (_('hash'), mask_hash(hash)),
+ ])
View
@@ -39,13 +39,10 @@ class Profile(ModelBase):
bio = models.TextField(null=True, blank=True,
verbose_name=_lazy(u'Biography'))
website = models.URLField(max_length=255, null=True, blank=True,
- verify_exists=False,
verbose_name=_lazy(u'Website'))
twitter = models.URLField(max_length=255, null=True, blank=True,
- verify_exists=False,
verbose_name=_lazy(u'Twitter URL'))
facebook = models.URLField(max_length=255, null=True, blank=True,
- verify_exists=False,
verbose_name=_lazy(u'Facebook URL'))
irc_handle = models.CharField(max_length=255, null=True, blank=True,
verbose_name=_lazy(u'IRC nickname'))
View
@@ -29,7 +29,6 @@
from sumo.decorators import ssl_required
from sumo.urlresolvers import reverse, split_path
from upload.tasks import _create_image_thumbnail
-from users.backends import Sha256Backend # Monkey patch User.set_password.
from users.forms import (ProfileForm, AvatarForm, EmailConfirmationForm,
AuthenticationForm, EmailChangeForm,
PasswordResetForm, BrowserIDRegisterForm,
View
@@ -199,10 +199,10 @@ class RevisionForm(forms.ModelForm):
'max_length': SUMMARY_LONG})
showfor_data = {
- 'oses': [(smart_str(c[0][0]), [(o.slug, smart_str(o.name)) for
+ 'oses': [(unicode(c[0][0]), [(o.slug, unicode(o.name)) for
o in c[1]]) for
c in GROUPED_OPERATING_SYSTEMS],
- 'versions': [(smart_str(c[0][0]), [(v.slug, smart_str(v.name)) for
+ 'versions': [(unicode(c[0][0]), [(v.slug, unicode(v.name)) for
v in c[1] if v.show_in_ui]) for
c in GROUPED_FIREFOX_VERSIONS]}
@@ -2373,7 +2373,7 @@ def test_section_edit_review_tags(self):
<p>test</p>
<p>test</p>
""")
- tags_to_save = ['foo', 'bar']
+ tags_to_save = ['bar', 'foo']
rev.save()
rev.review_tags.set(*tags_to_save)
View
@@ -24,13 +24,13 @@ def to_python(self, value):
return dict()
return value
- def get_db_prep_save(self, value):
+ def get_db_prep_save(self, value, connection):
"""Convert our JSON object to a string before we save"""
if not value:
return '{}'
if isinstance(value, dict):
value = json.dumps(value, cls=DjangoJSONEncoder)
- return super(JSONField, self).get_db_prep_save(value)
+ return super(JSONField, self).get_db_prep_save(value, connection)
# Tell South that this field isn't all that special
View
@@ -1,36 +0,0 @@
-import logging
-import logging.handlers
-
-from django.conf import settings
-
-import celery.conf
-import celery.log
-
-
-# Loggers created under the "z" namespace, e.g. "z.caching", will inherit the
-# configuration from the base z logger.
-log = logging.getLogger('mdn')
-
-fmt = ('%s: %%(asctime)s %%(name)s:%%(levelname)s %%(message)s '
- ':%%(pathname)s:%%(lineno)s' % settings.SYSLOG_TAG)
-fmt = getattr(settings, 'LOG_FORMAT', fmt)
-level = settings.LOG_LEVEL
-
-if settings.DEBUG:
- handler = logging.StreamHandler()
- formatter = logging.Formatter(fmt, datefmt='%H:%M:%S')
-else:
- SysLogger = logging.handlers.SysLogHandler
- handler = SysLogger(facility=SysLogger.LOG_LOCAL7)
- formatter = logging.Formatter(fmt)
-
-log.setLevel(level)
-handler.setLevel(level)
-handler.setFormatter(formatter)
-log.addHandler(handler)
-
-if not settings.DEBUG:
- task_log = logging.getLogger('mdn.celery')
- task_proxy = celery.log.LoggingProxy(task_log)
- celery.conf.CELERYD_LOG_FILE = task_proxy
- celery.conf.CELERYD_LOG_COLOR = False
Oops, something went wrong.

0 comments on commit 312a88e

Please sign in to comment.