Denis Kolodin avatar Denis Kolodin committed f3fe253

Add setup.py

Comments (0)

Files changed (23)

__init__.py

-# No any import there!

choices.py

-#!/usr/bin/env python
-#coding:utf-8
-# Author:  Denis Kolodin --<DenisKolodin@gmail.com>
-# Purpose: 
-# Created: 26.04.2011
-
-from django.utils.translation import ugettext as _
-
-########################################################################
-class Choices(object):
-
-    #----------------------------------------------------------------------
-    def __init__(self, **variants):
-        self.pairs = []
-        self.maps = {}
-        for name in variants:
-            code = variants[name]
-            self.pairs.append((code, _(name)))
-            self.maps[name] = code
-        self.pairs.sort(key=lambda item: item[0])
-        
-    #----------------------------------------------------------------------
-    def __iter__(self):
-        return iter(self.pairs)
-        
-    #----------------------------------------------------------------------
-    def __getattr__(self, key):
-        if key in self.maps:
-            return self.maps[key]
-        raise AttributeError("There isn't '{0}' in choices.".format(key))
-
-

decorators.py

-from django.http import HttpResponseBadRequest
-
-__all__ = ['expect_methods', 'meta_to_request']
-
-class ExpectMethods(object):
-    
-    def __init__(self, *methods):
-        self.methods = methods
-        
-    def __call__(self, func):
-        def view(request, *args, **kwargs):
-            if request.method not in self.methods:
-                return HttpResponseBadRequest("Method is not supported!")
-            return func(request, *args, **kwargs)
-        return view
-    
-
-expect_methods = ExpectMethods
-
-
-class MetaToRequest(object):
-    
-    def __init__(self, mapping):
-        self.mapping = mapping
-        
-    def __call__(self, func):
-        def view(request, *args, **kwargs):
-            qdict = request.POST if request.method == 'POST' else request.GET
-            q = qdict.copy() # make it mutable
-            for key in self.mapping:
-                if key in request.META:                    
-                    q.update({self.mapping[key]: request.META[key]})
-            if request.method == 'POST':
-                request.POST = q
-            else:
-                request.GET = q
-            return func(request, *args, **kwargs)
-        return view
-    
-meta_to_request = MetaToRequest
-
-

Empty file removed.

pretty.py

-from __future__ import division
-from math import ceil, floor
-
-def autocrop(value, max_length=100):
-    if max_length < 7:
-        raise ValueError("Too low length. Possible 7 chars min.")
-    t = value
-    half = max_length / 2
-    # 2 + 3 = 5 = len(" ... ")
-    llen = int(ceil(half) - 2)
-    rlen = int(floor(half) - 3)
-    return u"{0} ... {1}".format(t[:llen], t[-rlen:]) if len(t) > max_length else t
+from setuptools import setup, find_packages
+
+setup(
+    name = "djangogo",
+    version = "1.0",
+    url = "",
+    license = "BSD",
+    description = "Useful addons for Django.",
+    author = "Denis Kolodin",
+    packages = find_packages("src"),
+    package_dir = {'': "src"},
+    install_requires = ["setuptools"],
+)

src/djangogo/__init__.py

+# No any import there!

src/djangogo/choices.py

+#!/usr/bin/env python
+#coding:utf-8
+# Author:  Denis Kolodin --<DenisKolodin@gmail.com>
+# Purpose: 
+# Created: 26.04.2011
+
+from django.utils.translation import ugettext as _
+
+########################################################################
+class Choices(object):
+
+    #----------------------------------------------------------------------
+    def __init__(self, **variants):
+        self.pairs = []
+        self.maps = {}
+        for name in variants:
+            code = variants[name]
+            self.pairs.append((code, _(name)))
+            self.maps[name] = code
+        self.pairs.sort(key=lambda item: item[0])
+        
+    #----------------------------------------------------------------------
+    def __iter__(self):
+        return iter(self.pairs)
+        
+    #----------------------------------------------------------------------
+    def __getattr__(self, key):
+        if key in self.maps:
+            return self.maps[key]
+        raise AttributeError("There isn't '{0}' in choices.".format(key))
+
+

src/djangogo/decorators.py

+from django.http import HttpResponseBadRequest
+
+__all__ = ['expect_methods', 'meta_to_request']
+
+class ExpectMethods(object):
+    
+    def __init__(self, *methods):
+        self.methods = methods
+        
+    def __call__(self, func):
+        def view(request, *args, **kwargs):
+            if request.method not in self.methods:
+                return HttpResponseBadRequest("Method is not supported!")
+            return func(request, *args, **kwargs)
+        return view
+    
+
+expect_methods = ExpectMethods
+
+
+class MetaToRequest(object):
+    
+    def __init__(self, mapping):
+        self.mapping = mapping
+        
+    def __call__(self, func):
+        def view(request, *args, **kwargs):
+            qdict = request.POST if request.method == 'POST' else request.GET
+            q = qdict.copy() # make it mutable
+            for key in self.mapping:
+                if key in request.META:                    
+                    q.update({self.mapping[key]: request.META[key]})
+            if request.method == 'POST':
+                request.POST = q
+            else:
+                request.GET = q
+            return func(request, *args, **kwargs)
+        return view
+    
+meta_to_request = MetaToRequest
+
+

Empty file added.

src/djangogo/pretty.py

+from __future__ import division
+from math import ceil, floor
+
+def autocrop(value, max_length=100):
+    if max_length < 7:
+        raise ValueError("Too low length. Possible 7 chars min.")
+    t = value
+    half = max_length / 2
+    # 2 + 3 = 5 = len(" ... ")
+    llen = int(ceil(half) - 2)
+    rlen = int(floor(half) - 3)
+    return u"{0} ... {1}".format(t[:llen], t[-rlen:]) if len(t) > max_length else t

src/djangogo/tests/__init__.py

+from .cases import *

src/djangogo/tests/cases.py

+#!/usr/bin/env python
+#coding:utf-8
+# Author:  Denis Kolodin --<DenisKolodin@gmail.com>
+# Purpose: 
+# Created: 14.04.2011
+
+import unittest
+from django.http import HttpRequest
+from .models import TracingModel
+from .utils import DynamicModelsTest
+from ..choices import Choices
+from ..pretty import autocrop
+from ..decorators import *
+from ..views import *
+
+
+########################################################################
+class PrettyTest(unittest.TestCase):
+    
+    #----------------------------------------------------------------------
+    def test_autocrop(self):
+        source = "1234567890" * 10
+        self.assertEqual(autocrop(source, 200), source)
+        self.assertEqual(autocrop(source, 100), source)
+        self.assertEqual(autocrop(source, 90), source[:43] + " ... " + source[-42:])
+        autocrop(source, 7) # No exceptions
+        self.assertRaises(ValueError, autocrop, source, 6) # less than 7        
+        
+
+########################################################################
+class DecoratorsTest(unittest.TestCase):
+    
+    #----------------------------------------------------------------------
+    def test_expect_methods(self):
+        def dummy_view(request):
+            return HttpResponse("Dummy View!")
+        dummy_view = expect_methods('POST')(dummy_view)
+        request = HttpRequest()
+        request.method = 'POST'
+        response = dummy_view(request)
+        self.assertIsInstance(response, HttpResponse)
+        self.assertEqual(response.content, "Dummy View!")
+        request.method = 'GET'
+        response = dummy_view(request)
+        self.assertIsInstance(response, HttpResponseBadRequest)
+        
+    #----------------------------------------------------------------------
+    def test_meta_to_request_normal(self):
+        def assert_view(request):
+            self.assertIn('REMOTE_ADDR', request.META)
+            self.assertIn('ip_address', request.POST)
+            self.assertNotIn('ip_address', request.GET)
+            self.assertEqual(request.META['REMOTE_ADDR'], request.POST['ip_address'])
+            self.assertEqual(request.POST['ip_address'], '127.0.0.0')
+            return HttpResponse("Assert View!")
+        assert_view = meta_to_request({'REMOTE_ADDR': 'ip_address'})(assert_view)
+        request = HttpRequest()
+        request.method = 'POST'
+        request.META = {'REMOTE_ADDR': '127.0.0.0'}
+        response = assert_view(request)
+        self.assertIsInstance(response, HttpResponse)
+        self.assertEqual(response.content, "Assert View!")
+        
+    #----------------------------------------------------------------------
+    def test_meta_to_request_empty(self):
+        def assert_view(request):
+            self.assertNotIn('REMOTE_ADDR', request.META)
+            self.assertNotIn('ip_address', request.POST)
+            return HttpResponse("Assert View!")
+        assert_view = meta_to_request({'REMOTE_ADDR': 'ip_address'})(assert_view)
+        request = HttpRequest()
+        request.method = 'POST'
+        response = assert_view(request)
+        self.assertIsInstance(response, HttpResponse)
+        self.assertEqual(response.content, "Assert View!")
+                
+        
+########################################################################
+class ViewsTest(DynamicModelsTest):
+
+    apps = ('djangogo.tests',)
+
+    #----------------------------------------------------------------------
+    def make_request(self, data={}, post=True):
+        request = HttpRequest()
+        if post:
+            request.method = 'POST'
+            request.POST = data
+        else:
+            request.method = 'GET'
+            request.GET = data
+        return request
+                
+    #----------------------------------------------------------------------
+    def test_trace_model(self):
+        self.assertEqual(TracingModel.objects.count(), 0)
+        view = trace_model(TracingModel)
+        
+        response = view(self.make_request({'afield': '12345'})) # Give as text
+        self.assertIsInstance(response, HttpResponse)
+        self.assertEqual(TracingModel.objects.count(), 1) # Object Traced!
+        self.assertEqual(TracingModel.objects.get(pk=1).afield, 12345)
+        
+        response = view(self.make_request({'afield': '500'}, post=False)) # Give as text by GET
+        self.assertIsInstance(response, HttpResponse)
+        self.assertEqual(TracingModel.objects.count(), 2) # Object Traced!
+        self.assertEqual(TracingModel.objects.get(pk=2).afield, 500)
+        
+        response = view(self.make_request({'afield': ''})) # invalid data
+        self.assertIsInstance(response, HttpResponseBadRequest)
+        self.assertEqual(TracingModel.objects.count(), 2) # Not Traced!
+
+        response = view(self.make_request()) # empty data
+        self.assertIsInstance(response, HttpResponseBadRequest)
+        self.assertEqual(TracingModel.objects.count(), 2) # Not Traced!
+                
+
+########################################################################
+class ChoicesTest(unittest.TestCase):
+
+    #----------------------------------------------------------------------
+    def test_getattr(self):
+        choices = Choices(First=1, Second=2, Last=-1)
+        self.assertTrue(hasattr(choices, 'First'))
+        self.assertEqual(choices.First, 1)
+        self.assertTrue(hasattr(choices, 'Second'))
+        self.assertEqual(choices.Second, 2)
+        self.assertTrue(hasattr(choices, 'Last'))
+        self.assertEqual(choices.Last, -1)
+        # Get parent's
+        self.assertIsNotNone(getattr(choices, '__hash__'))
+
+    #----------------------------------------------------------------------
+    def test_iter(self):
+        choices = Choices(First=1, Second=2, Last=-1)
+        l = list(choices)
+        self.assertEqual(len(l), 3)
+        self.assertIn((1, 'First'), l)
+        self.assertIn((2, 'Second'), l)
+        self.assertIn((-1, 'Last'), l)
+        
+    #----------------------------------------------------------------------
+    def test_bad(self):
+        choices = Choices(First=1, Second=2)
+        self.assertRaises(AttributeError, getattr, choices, 'NotExist')
+        
+        
+if __name__=='__main__':
+    unittest.main()

src/djangogo/tests/models.py

+from django.db import models
+
+class TracingModel(models.Model):
+    afield = models.PositiveIntegerField()
+

src/djangogo/tests/utils.py

+from django.conf import settings
+from django.core.management import call_command
+from django.db.models import loading
+from django.test import TestCase
+
+########################################################################
+class DynamicModelsTest(TestCase):
+
+    apps = ()
+    no_middleware = ()
+    
+    #----------------------------------------------------------------------
+    def _pre_setup(self):
+        # Add the models to the db.
+        self._original_installed_apps = list(settings.INSTALLED_APPS)
+        self._original_middleware_classes = list(settings.MIDDLEWARE_CLASSES)
+        for app in self.apps:
+            settings.INSTALLED_APPS.append(app)
+        for exclude in self.no_middleware:
+            settings.MIDDLEWARE_CLASSES = []
+            for mw in self._original_middleware_classes:
+                if not mw.endswith(exclude):
+                    settings.MIDDLEWARE_CLASSES.append(mw)
+        loading.cache.loaded = False
+        call_command('syncdb', interactive=False, verbosity=0)
+        # Call the original method that does the fixtures etc.
+        super(DynamicModelsTest, self)._pre_setup()
+
+    #----------------------------------------------------------------------
+    def _post_teardown(self):
+        # Call the original method.
+        super(DynamicModelsTest, self)._post_teardown()
+        # Restore the settings.
+        settings.MIDDLEWARE_CLASSES = self._original_middleware_classes
+        settings.INSTALLED_APPS = self._original_installed_apps
+        loading.cache.loaded = False    

src/djangogo/utils.py

+try:
+    from functools import wraps
+except ImportError:
+    from django.utils.functional import wraps
+
+import inspect
+from django.db import models
+from django.core.signals import Signal
+
+def disable_for_loaddata(signal_handler):
+    @wraps(signal_handler)
+    def wrapper(*args, **kwargs):
+        for fr in inspect.stack():
+            if inspect.getmodulename(fr[1]) == 'loaddata':
+                return
+        signal_handler(*args, **kwargs)
+    return wrapper
+
+
+def accompany(field_name):
+    def _accompany(modelclass):
+        sender = getattr(modelclass, field_name).field.related.parent_model
+
+        @disable_for_loaddata
+        def create_handler(sender, instance, created, **kwargs):
+            if created:
+                dependent = modelclass()
+                setattr(dependent, field_name, instance)
+                dependent.save()
+        models.signals.post_save.connect(create_handler, sender=sender, weak=False)
+
+        def delete_handler(sender, instance, **kwargs):
+            dependent = modelclass.objects.get(**{field_name: instance})
+            dependent.delete()
+        models.signals.pre_delete.connect(delete_handler, sender=sender, weak=False)
+
+        return modelclass
+
+    return _accompany
+                

src/djangogo/views.py

+from django.http import HttpResponse, HttpResponseBadRequest
+from django.forms import ModelForm
+
+def trace_model(modelclass):
+    # Creating new form
+    class Meta:
+        model = modelclass    
+    modelform = type(modelclass.__name__ + 'TraceForm', (ModelForm,), {'Meta': Meta})
+    # Create view
+    def modeltraceview(request):
+        form = modelform(request.POST if request.method == 'POST' else request.GET)
+        if form.is_valid():
+            form.save()
+            return HttpResponse()
+        return HttpResponseBadRequest()
+    return modeltraceview
+

tests/__init__.py

-from .cases import *

tests/cases.py

-#!/usr/bin/env python
-#coding:utf-8
-# Author:  Denis Kolodin --<DenisKolodin@gmail.com>
-# Purpose: 
-# Created: 14.04.2011
-
-import unittest
-from django.http import HttpRequest
-from .models import TracingModel
-from .utils import DynamicModelsTest
-from ..choices import Choices
-from ..pretty import autocrop
-from ..decorators import *
-from ..views import *
-
-
-########################################################################
-class PrettyTest(unittest.TestCase):
-    
-    #----------------------------------------------------------------------
-    def test_autocrop(self):
-        source = "1234567890" * 10
-        self.assertEqual(autocrop(source, 200), source)
-        self.assertEqual(autocrop(source, 100), source)
-        self.assertEqual(autocrop(source, 90), source[:43] + " ... " + source[-42:])
-        autocrop(source, 7) # No exceptions
-        self.assertRaises(ValueError, autocrop, source, 6) # less than 7        
-        
-
-########################################################################
-class DecoratorsTest(unittest.TestCase):
-    
-    #----------------------------------------------------------------------
-    def test_expect_methods(self):
-        def dummy_view(request):
-            return HttpResponse("Dummy View!")
-        dummy_view = expect_methods('POST')(dummy_view)
-        request = HttpRequest()
-        request.method = 'POST'
-        response = dummy_view(request)
-        self.assertIsInstance(response, HttpResponse)
-        self.assertEqual(response.content, "Dummy View!")
-        request.method = 'GET'
-        response = dummy_view(request)
-        self.assertIsInstance(response, HttpResponseBadRequest)
-        
-    #----------------------------------------------------------------------
-    def test_meta_to_request_normal(self):
-        def assert_view(request):
-            self.assertIn('REMOTE_ADDR', request.META)
-            self.assertIn('ip_address', request.POST)
-            self.assertNotIn('ip_address', request.GET)
-            self.assertEqual(request.META['REMOTE_ADDR'], request.POST['ip_address'])
-            self.assertEqual(request.POST['ip_address'], '127.0.0.0')
-            return HttpResponse("Assert View!")
-        assert_view = meta_to_request({'REMOTE_ADDR': 'ip_address'})(assert_view)
-        request = HttpRequest()
-        request.method = 'POST'
-        request.META = {'REMOTE_ADDR': '127.0.0.0'}
-        response = assert_view(request)
-        self.assertIsInstance(response, HttpResponse)
-        self.assertEqual(response.content, "Assert View!")
-        
-    #----------------------------------------------------------------------
-    def test_meta_to_request_empty(self):
-        def assert_view(request):
-            self.assertNotIn('REMOTE_ADDR', request.META)
-            self.assertNotIn('ip_address', request.POST)
-            return HttpResponse("Assert View!")
-        assert_view = meta_to_request({'REMOTE_ADDR': 'ip_address'})(assert_view)
-        request = HttpRequest()
-        request.method = 'POST'
-        response = assert_view(request)
-        self.assertIsInstance(response, HttpResponse)
-        self.assertEqual(response.content, "Assert View!")
-                
-        
-########################################################################
-class ViewsTest(DynamicModelsTest):
-
-    apps = ('djangogo.tests',)
-
-    #----------------------------------------------------------------------
-    def make_request(self, data={}, post=True):
-        request = HttpRequest()
-        if post:
-            request.method = 'POST'
-            request.POST = data
-        else:
-            request.method = 'GET'
-            request.GET = data
-        return request
-                
-    #----------------------------------------------------------------------
-    def test_trace_model(self):
-        self.assertEqual(TracingModel.objects.count(), 0)
-        view = trace_model(TracingModel)
-        
-        response = view(self.make_request({'afield': '12345'})) # Give as text
-        self.assertIsInstance(response, HttpResponse)
-        self.assertEqual(TracingModel.objects.count(), 1) # Object Traced!
-        self.assertEqual(TracingModel.objects.get(pk=1).afield, 12345)
-        
-        response = view(self.make_request({'afield': '500'}, post=False)) # Give as text by GET
-        self.assertIsInstance(response, HttpResponse)
-        self.assertEqual(TracingModel.objects.count(), 2) # Object Traced!
-        self.assertEqual(TracingModel.objects.get(pk=2).afield, 500)
-        
-        response = view(self.make_request({'afield': ''})) # invalid data
-        self.assertIsInstance(response, HttpResponseBadRequest)
-        self.assertEqual(TracingModel.objects.count(), 2) # Not Traced!
-
-        response = view(self.make_request()) # empty data
-        self.assertIsInstance(response, HttpResponseBadRequest)
-        self.assertEqual(TracingModel.objects.count(), 2) # Not Traced!
-                
-
-########################################################################
-class ChoicesTest(unittest.TestCase):
-
-    #----------------------------------------------------------------------
-    def test_getattr(self):
-        choices = Choices(First=1, Second=2, Last=-1)
-        self.assertTrue(hasattr(choices, 'First'))
-        self.assertEqual(choices.First, 1)
-        self.assertTrue(hasattr(choices, 'Second'))
-        self.assertEqual(choices.Second, 2)
-        self.assertTrue(hasattr(choices, 'Last'))
-        self.assertEqual(choices.Last, -1)
-        # Get parent's
-        self.assertIsNotNone(getattr(choices, '__hash__'))
-
-    #----------------------------------------------------------------------
-    def test_iter(self):
-        choices = Choices(First=1, Second=2, Last=-1)
-        l = list(choices)
-        self.assertEqual(len(l), 3)
-        self.assertIn((1, 'First'), l)
-        self.assertIn((2, 'Second'), l)
-        self.assertIn((-1, 'Last'), l)
-        
-    #----------------------------------------------------------------------
-    def test_bad(self):
-        choices = Choices(First=1, Second=2)
-        self.assertRaises(AttributeError, getattr, choices, 'NotExist')
-        
-        
-if __name__=='__main__':
-    unittest.main()

tests/models.py

-from django.db import models
-
-class TracingModel(models.Model):
-    afield = models.PositiveIntegerField()
-

tests/utils.py

-from django.conf import settings
-from django.core.management import call_command
-from django.db.models import loading
-from django.test import TestCase
-
-########################################################################
-class DynamicModelsTest(TestCase):
-
-    apps = ()
-    no_middleware = ()
-    
-    #----------------------------------------------------------------------
-    def _pre_setup(self):
-        # Add the models to the db.
-        self._original_installed_apps = list(settings.INSTALLED_APPS)
-        self._original_middleware_classes = list(settings.MIDDLEWARE_CLASSES)
-        for app in self.apps:
-            settings.INSTALLED_APPS.append(app)
-        for exclude in self.no_middleware:
-            settings.MIDDLEWARE_CLASSES = []
-            for mw in self._original_middleware_classes:
-                if not mw.endswith(exclude):
-                    settings.MIDDLEWARE_CLASSES.append(mw)
-        loading.cache.loaded = False
-        call_command('syncdb', interactive=False, verbosity=0)
-        # Call the original method that does the fixtures etc.
-        super(DynamicModelsTest, self)._pre_setup()
-
-    #----------------------------------------------------------------------
-    def _post_teardown(self):
-        # Call the original method.
-        super(DynamicModelsTest, self)._post_teardown()
-        # Restore the settings.
-        settings.MIDDLEWARE_CLASSES = self._original_middleware_classes
-        settings.INSTALLED_APPS = self._original_installed_apps
-        loading.cache.loaded = False    

utils.py

-try:
-    from functools import wraps
-except ImportError:
-    from django.utils.functional import wraps
-
-import inspect
-from django.db import models
-from django.core.signals import Signal
-
-def disable_for_loaddata(signal_handler):
-    @wraps(signal_handler)
-    def wrapper(*args, **kwargs):
-        for fr in inspect.stack():
-            if inspect.getmodulename(fr[1]) == 'loaddata':
-                return
-        signal_handler(*args, **kwargs)
-    return wrapper
-
-
-def accompany(field_name):
-    def _accompany(modelclass):
-        sender = getattr(modelclass, field_name).field.related.parent_model
-
-        @disable_for_loaddata
-        def create_handler(sender, instance, created, **kwargs):
-            if created:
-                dependent = modelclass()
-                setattr(dependent, field_name, instance)
-                dependent.save()
-        models.signals.post_save.connect(create_handler, sender=sender, weak=False)
-
-        def delete_handler(sender, instance, **kwargs):
-            dependent = modelclass.objects.get(**{field_name: instance})
-            dependent.delete()
-        models.signals.pre_delete.connect(delete_handler, sender=sender, weak=False)
-
-        return modelclass
-
-    return _accompany
-                

views.py

-from django.http import HttpResponse, HttpResponseBadRequest
-from django.forms import ModelForm
-
-def trace_model(modelclass):
-    # Creating new form
-    class Meta:
-        model = modelclass    
-    modelform = type(modelclass.__name__ + 'TraceForm', (ModelForm,), {'Meta': Meta})
-    # Create view
-    def modeltraceview(request):
-        form = modelform(request.POST if request.method == 'POST' else request.GET)
-        if form.is_valid():
-            form.save()
-            return HttpResponse()
-        return HttpResponseBadRequest()
-    return modeltraceview
-
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.