Luke Plant avatar Luke Plant committed ee607dc

Added source for fake 'datetime' and 'date'.

Comments (0)

Files changed (1)

anonymizer/base.py

+from datetime import datetime
+import random
+randrange = random.SystemRandom().randrange
+
 from django.db import transaction
 from django.db.utils import IntegrityError
 from faker import Faker
 
     def _get_allowed_value(self, source, field):
         retval = source()
+        if field is None:
+            return retval
 
         # Enforce unique.  Eensure we don't set the same values, as either
         # any of the existing values, or any of the new ones we make up.
 
         return retval
 
+    ### Public interace ##
+
+    def datetime(self, obj=None, field=None, val=None):
+        """
+        Returns a random datetime. If 'val' is passed, a datetime within two
+        years of that date will be returned.
+        """
+        if val is None:
+            source = lambda: datetime.fromtimestamp(randrange(1, 2100000000))
+        else:
+            source = lambda: datetime.fromtimestamp(int(val.strftime("%s")) +
+                                                    randrange(-365*24*3600*2, 365*24*3600*2))
+        return self._get_allowed_value(source, field)
+
+    def date(self, obj=None, field=None, val=None):
+        """
+        Like datetime, but truncated to be a date only
+        """
+        d = self.datetime(obj=obj, field=field, val=val)
+        return d.date()
+
+    ## Other attributes provided by 'Faker':
+
+    # username
+    # first_name
+    # last_name
+    # name
+    # full_address
+    # phonenumber
+    # streetaddress
+    # city
+    # state
+    # zip_code
+    # lorem
+
     def __getattr__(self, name):
         # we delegate most calls to faker, but add checks
         source = getattr(self.faker, name)
 
         def func(*args, **kwargs):
             field = kwargs.get('field', None)
-            if field is not None:
-                return self._get_allowed_value(source, field)
-            else:
-                return source()
+            return self._get_allowed_value(source, field)
         return func
 
 
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.