Commits

Valentin Golev  committed 08c7bb1

+3 tests. Field types. QuerySet

  • Participants
  • Parent commits ddb6420

Comments (0)

Files changed (9)

File mon_django/auth/forms.py

                 'email': user.email,
                 'domain': domain,
                 'site_name': site_name,
-                'uid': int_to_base36(user.id),
+                'uid': user.id,
                 'user': user,
                 'token': token_generator.make_token(user),
                 'protocol': use_https and 'https' or 'http',

File mon_django/auth/models.py

 import datetime
+import re
 
 from django.utils.encoding import smart_str
 from django.utils.hashcompat import md5_constructor, sha_constructor
 from django.core import exceptions
 
 from mon_django.core import get_db
+from mon_django.core.fields import AutoField, DateTimeField
+from mon_django.core.queryset import QuerySet
 
 UNUSABLE_PASSWORD = '!' # This will never be a valid hash
 
         collection.ensure_index('username', unique=True)
         return collection
 
-    def get(self, **kwargs):
+    def _get_query(self, **kwargs):
         query = {}
 
-        for p in kwargs.iterkeys():
+        for p, v in kwargs.iteritems():
+            lst = p.split('__', 1)
+            mod = ''
+            if len(lst) > 1:
+                p, mod = lst
+
             if p == 'pk' or p == 'id':
-                query['_id'] = kwargs[p]
-            elif p in self.model.valid_params:
-                query[p] = kwargs[p]
+                p = '_id'
+
+            if p in self.model.field_types:
+                v = self.model.field_types[p].get_prep_value(v)
+
+            if p in self.model.valid_fields:
+                if not mod:
+                    query[p] = v
+                elif mod == 'iexact':
+                    query[p] = re.compile(v, re.I)
+                else:
+                    raise TypeError("'%s' is an invalid modifier for this function" % mod)     
             else:
-                raise TypeError("'%s' is an invalid keyword argument for this function" % p) 
+                raise TypeError("'%s' is an invalid keyword argument for this function" % p)     
+        return query
 
+    def get(self, **kwargs):
+        query = self._get_query(**kwargs)
         result = self.get_collection().find(query)
         num = result.count()
         if num == 1:
         raise self.model.MultipleObjectsReturned("get() returned more than one User -- it returned %s! Lookup parameters were %s"
                 % (num, kwargs))
 
+    def filter(self, **kwargs):
+        query = self._get_query(**kwargs)
+        result = self.get_collection().find(query)
+        return QuerySet(self.model, result)
+
+    def all(self):
+        return self
+
 class User(object):
     objects = UserManager()
+    _default_manager = objects
 
-    valid_params = ('username', 'first_name', 'last_name', 'email', 'password',
+    valid_fields = ('username', 'first_name', 'last_name', 'email', 'password',
                     'is_staff', 'is_active', 'is_superuser', 'last_login',
                     'date_joined', 'groups', 'user_permissions', '_id')
 
     valid_attrs = ('_params', 'backend')
 
+    field_types = {
+        'last_login' : DateTimeField(),
+        '_id' : AutoField()
+    }
+
     DoesNotExist = exceptions.ObjectDoesNotExist
     MultipleObjectsReturned = exceptions.MultipleObjectsReturned
 
+    class Meta:
+        object_name = 'User'
+    _meta = Meta()
+
     def __init__(self, **kwargs):
         self._params = {}
         for p in kwargs.iterkeys():
-            if p in self.valid_params:
-                self._params[p] = kwargs[p]
+            if p in self.valid_fields:
+                if p in self.field_types:
+                    self._params[p] = self.field_types[p].to_python(kwargs[p])
+                else:
+                    self._params[p] = kwargs[p]
             else:
                 raise TypeError("'%s' is an invalid keyword argument for this function" % p) 
 
             name = '_id'
         if name in self.valid_attrs:
             return object.__getattr__(self, name)
-        if not name in self.valid_params:
+        if not name in self.valid_fields:
             raise AttributeError("'User' object has no attribute '%s'" % name)
         try:
             return self._params[name]
         if name in self.valid_attrs:
             object.__setattr__(self, name, value)
             return
-        if not name in self.valid_params:
+        if not name in self.valid_fields:
             raise AttributeError("'User' object has no attribute '%s'" % name)
         self._params[name] = value
 

File mon_django/auth/tests/views.py

         self.login()
         response = self.client.get('/logout/')
         self.assertEquals(200, response.status_code)
-        print response
         self.assert_('Logged out' in response.content)
         self.confirm_logged_out()
 

File mon_django/auth/views.py

     assert uidb36 is not None and token is not None # checked by URLconf
     if post_reset_redirect is None:
         post_reset_redirect = reverse('mon_django.auth.views.password_reset_complete')
-    try:
-        uid_int = base36_to_int(uidb36)
-    except ValueError:
-        raise Http404
+    
+    uid = uidb36
 
-    user = get_object_or_404(User, id=uid_int)
+    user = get_object_or_404(User, id=uid)
     context_instance = RequestContext(request)
 
     if token_generator.check_token(user, token):

File mon_django/core/fields.py

+import datetime
+import time
+
+from pymongo.objectid import ObjectId
+
+class Field(object):
+    def to_python(self, value):
+        return value
+    def get_prep_value(self, value):
+        return value
+
+class AutoField(Field):
+    def get_prep_value(self, value):
+        if value is None:
+            return value
+        if isinstance(value, ObjectId):
+            return value
+
+        return ObjectId(value)
+
+class DateTimeField(Field):
+    def to_python(self, value):
+        if value is None:
+            return value
+        if isinstance(value, datetime.datetime):
+            return value
+        if isinstance(value, datetime.date):
+            return datetime.datetime(value.year, value.month, value.day)
+
+        return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6])
+
+

File mon_django/core/models.py

Empty file added.

File mon_django/core/queryset.py

+class QuerySet(object):
+    def __init__(self, cls, cursor):
+        self.cls = cls
+        self.cursor = cursor
+    
+    def __len__(self):
+        return self.cursor.count(with_limit_and_skip=True)
+
+    def __iter__(self):
+        return (self.cls(**i) for i in self.cursor)

File mon_django/core/shortcuts.py

Empty file added.

File testproject/settings.py

 
 INSTALLED_APPS = (
 #    'django.contrib.auth',
-    'django.contrib.contenttypes',
+#    'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
 #    'django.contrib.messages',