Commits

Waldemar Kornewald  committed d29cd06

initial import

  • Participants

Comments (0)

Files changed (7)

+syntax: glob
+.project
+.pydevproject
+.settings
+*~
+*.orig
+*.pyc
+*.pyo
+*.swp
+*.tmp
+desktop.ini
+nbproject

File __init__.py

Empty file added.
+# -*- coding: utf-8 -*-
+from django.conf import settings
+from django.core.serializers.json import DjangoJSONEncoder
+from django.http import HttpResponse
+from django.utils import simplejson
+from django.utils.encoding import force_unicode
+from django.utils.functional import Promise
+
+class LazyEncoder(DjangoJSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, Promise):
+            return force_unicode(obj)
+        return super(LazyEncoder, self).default(obj)
+
+class JSONResponse(HttpResponse):
+    def __init__(self, pyobj, **kwargs):
+        super(JSONResponse, self).__init__(
+            simplejson.dumps(pyobj, cls=LazyEncoder),
+            content_type='application/json; charset=%s' %
+                            settings.DEFAULT_CHARSET,
+            **kwargs)
+
+class TextResponse(HttpResponse):
+    def __init__(self, string='', **kwargs):
+        super(TextResponse, self).__init__(string,
+            content_type='text/plain; charset=%s' % settings.DEFAULT_CHARSET,
+            **kwargs)

File middleware.py

+# -*- coding: utf-8 -*-
+from django.conf import settings
+from django.utils.cache import patch_cache_control
+from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
+from google.appengine.ext import db
+
+LOGIN_REQUIRED_PREFIXES = getattr(settings, 'LOGIN_REQUIRED_PREFIXES', ())
+NO_LOGIN_REQUIRED_PREFIXES = getattr(settings, 'NO_LOGIN_REQUIRED_PREFIXES', ())
+
+class LoginRequiredMiddleware(object):
+    """
+    Redirects to login page if request path begins with a
+    LOGIN_REQURED_PREFIXES prefix. You can also specify
+    NO_LOGIN_REQUIRED_PREFIXES which take precedence.
+    """
+    def process_request(self, request):
+        for prefix in NO_LOGIN_REQUIRED_PREFIXES:
+            if request.path.startswith(prefix):
+                return None
+        for prefix in LOGIN_REQUIRED_PREFIXES:
+            if request.path.startswith(prefix) and \
+                    not request.user.is_authenticated():
+                from django.contrib.auth.views import redirect_to_login
+                return redirect_to_login(request.get_full_path())
+        return None
+
+class NoHistoryCacheMiddleware(object):
+    """
+    If user is authenticated we disable browser caching of pages in history.
+    """
+    def process_response(self, request, response):
+        if 'Expires' not in response and \
+                'Cache-Control' not in response and \
+                hasattr(request, 'session') and \
+                request.user.is_authenticated():
+            patch_cache_control(response,
+                no_store=True, no_cache=True, must_revalidate=True, max_age=0)
+        return response
+
+class ErrorMiddleware(object):
+    """Displays a default template on CapabilityDisabledError."""
+    def process_exception(self, request, exception):
+        if isinstance(exception, CapabilityDisabledError):
+            return maintenance(request)
+        elif isinstance(exception, db.Timeout):
+            return server_error(request)
+# -*- coding: utf-8 -*-
+from .utils import object_list_to_table, equal_lists
+from django.test import TestCase as DjangoTestCase
+from google.appengine.ext import db
+import os
+import unittest
+
+class TestCase(DjangoTestCase):
+    def setUp(self):
+        self.setup()
+
+    def tearDown(self):
+        self.teardown()
+
+    def setup(self):
+        pass
+
+    def teardown(self):
+        pass
+
+class ModelTestCase(TestCase):
+    """
+    A test case for models that provides an easy way to validate the DB
+    contents against a given list of row-values.
+
+    You have to specify the model to validate using the 'model' attribute:
+    class MyTestCase(ModelTestCase):
+        model = MyModel
+    """
+    def validate_state(self, columns, *state_table):
+        """
+        Validates that the DB contains exactly the values given in the state
+        table. The list of columns is given in the columns tuple.
+
+        Example:
+        self.validate_state(
+            ('a', 'b', 'c'),
+            (1, 2, 3),
+            (11, 12, 13),
+        )
+        validates that the table contains exactly two rows and that their
+        'a', 'b', and 'c' attributes are 1, 2, 3 for one row and 11, 12, 13
+        for the other row. The order of the rows doesn't matter.
+        """
+        current_state = object_list_to_table(columns,
+            self.model.all())[1:]
+        if not equal_lists(current_state, state_table):
+            print 'DB state not valid:'
+            print 'Current state:'
+            print columns
+            for state in current_state:
+                print state
+            print 'Should be:'
+            for state in state_table:
+                print state
+            self.fail('DB state not valid')
+# -*- coding: utf-8 -*-
+"""
+Imports urlpatterns from apps, so we can have nice plug-n-play installation. :)
+"""
+from django.conf.urls.defaults import *
+from django.conf import settings
+
+IGNORE_APP_URLSAUTO = getattr(settings, 'IGNORE_APP_URLSAUTO', ())
+check_app_imports = getattr(settings, 'check_app_imports', None)
+
+urlpatterns = patterns('')
+
+for app in settings.INSTALLED_APPS:
+    if app == 'ragendja' or app.startswith('django.') or \
+            app in IGNORE_APP_URLSAUTO:
+        continue
+    appname = app.rsplit('.', 1)[-1]
+    try:
+        if check_app_imports:
+            check_app_imports(app)
+        module = __import__(app + '.urlsauto', {}, {}, [''])
+    except ImportError:
+        pass
+    else:
+        if hasattr(module, 'urlpatterns'):
+            urlpatterns += patterns('', (r'^%s/' % appname,
+                                         include(app + '.urlsauto')),)
+        if hasattr(module, 'rootpatterns'):
+            urlpatterns += module.rootpatterns
+# -*- coding: utf-8 -*-
+from django.utils._threading_local import local
+
+def make_tls_property(default=None):
+    """Creates a class-wide instance property with a thread-specific value."""
+    class TLSProperty(object):
+        def __init__(self):
+            self.local = local()
+
+        def __get__(self, instance, cls):
+            if not instance:
+                return self
+            return self.value
+
+        def __set__(self, instance, value):
+            self.value = value
+
+        def _get_value(self):
+            return getattr(self.local, 'value', default)
+        def _set_value(self, value):
+            self.local.value = value
+        value = property(_get_value, _set_value)
+
+    return TLSProperty()
+
+def getattr_by_path(obj, attr, *default):
+    """Like getattr(), but can go down a hierarchy like 'attr.subattr'"""
+    value = obj
+    for part in attr.split('.'):
+        if not hasattr(value, part) and len(default):
+            return default[0]
+        value = getattr(value, part)
+        if callable(value):
+            value = value()
+    return value
+
+def subdict(data, *attrs):
+    """Returns a subset of the keys of a dictionary."""
+    result = {}
+    result.update([(key, data[key]) for key in attrs])
+    return result
+
+def equal_lists(left, right):
+    """
+    Compares two lists and returs True if they contain the same elements, but
+    doesn't require that they have the same order.
+    """
+    right = list(right)
+    if len(left) != len(right):
+        return False
+    for item in left:
+        if item in right:
+            del right[right.index(item)]
+        else:
+            return False
+    return True
+
+def object_list_to_table(headings, dict_list):
+    """
+    Converts objects to table-style list of rows with heading:
+
+    Example:
+    x.a = 1
+    x.b = 2
+    x.c = 3
+    y.a = 11
+    y.b = 12
+    y.c = 13
+    object_list_to_table(('a', 'b', 'c'), [x, y])
+    results in the following (dict keys reordered for better readability):
+    [
+        ('a', 'b', 'c'),
+        (1, 2, 3),
+        (11, 12, 13),
+    ]
+    """
+    return [headings] + [tuple([getattr_by_path(row, heading, None)
+                                for heading in headings])
+                         for row in dict_list]
+
+def dict_list_to_table(headings, dict_list):
+    """
+    Converts dict to table-style list of rows with heading:
+
+    Example:
+    dict_list_to_table(('a', 'b', 'c'),
+        [{'a': 1, 'b': 2, 'c': 3}, {'a': 11, 'b': 12, 'c': 13}])
+    results in the following (dict keys reordered for better readability):
+    [
+        ('a', 'b', 'c'),
+        (1, 2, 3),
+        (11, 12, 13),
+    ]
+    """
+    return [headings] + [tuple([row[heading] for heading in headings])
+                         for row in dict_list]