Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

first working version

  • Loading branch information...
commit b7f48d7dcb2aeb815a934b1e72601b4b10d40d49 1 parent 469b494
@sbaechler authored
View
1  .gitignore
@@ -0,0 +1 @@
+*.pyc
View
18 README.rst
@@ -7,7 +7,8 @@ Django-Scaffolding creates placeholder data for your app.
Usage
=====
-Create a Scaffolding class within your model which contains the callbacks to fill it with the necesarry data::
+Create a Scaffolding class within your model which contains the callbacks to fill it with the necesarry data.
+The syntax is ScaffoldingClass, kwargs::
import scaffolding
@@ -15,18 +16,23 @@ Create a Scaffolding class within your model which contains the callbacks to fil
first_name = models.CharField('First Name', max_length=32)
last_name = models.CharField('Last Name', max_length=32)
comment = models.TextField('Comment')
+ contest = models.ForeignKey(Contest)
...
class Scaffolding:
- first_name = scaffolding.FirstNname(max_length=32)
- last_name = scaffolding.LastNname(max_length=32)
- comment = scaffolding.LoremIpsum(paragraphs=1)
-
+ first_name = scaffolding.FirstName, {'max_length':32}
+ last_name = scaffolding.LastName, {'max_length':32}
+ comment = scaffolding.LoremIpsum, {'paragraphs':1}
+ contest_id = scaffolding.RandInt, {'min': 1, 'max': 2 }
+
+Mind the syntax for ForeignKey fields. You assign an integer to field_id. Make sure the element
+does exist.
+
Run the management command to create the data::
manage.py scaffold myapp.MyModel 20
-The number stands for the amout of entries.
+The number stands for the amout of entries to be created.
View
61 scaffolding/__init__.py
@@ -3,25 +3,39 @@
from scaffolding import library
from library.lorem_ipsum import LOREM_IPSUM
-class Name(object):
- """ Generates a random name. gender can be 'male' or 'female' or 'm' or 'f'.
+class Tube(object):
+ """ The base class for scaffolding objects.
"""
- def __init__(self, max_length=30, gender=None, *args, **kwargs):
- self.max_length = max_length
- self.first_names = library.FirstNames(gender=gender)
- self.last_names = library.LastNames()
+ def __init__(self, **kwargs):
+ self.count = kwargs.get('count')
+ self.cls = kwargs.get('cls')
def __iter__(self):
return self
def next(self):
+ raise NotImplementedError('You need to implement your own next method.')
+
+#---------- custom classes -----------------
+
+class Name(Tube):
+ """ Generates a random name. <gender> can be 'male', 'female', 'm' or 'f'.
+ """
+ def __init__(self, max_length=30, gender=None, **kwargs):
+ super(Name, self).__init__(**kwargs)
+ self.max_length = max_length
+ self.first_names = library.FirstNames(gender=gender)
+ self.last_names = library.LastNames()
+
+ def next(self):
return '%s %s'[:self.max_length] % (self.first_names.next(), self.last_names.next())
-class LoremIpsum(object):
+class LoremIpsum(Tube):
""" Generates a Lorem Ipsum Text. The number of paragraphs is defined in paragraphs.
"""
- def __init__(self, paragraphs=7, max_length=None, text=LOREM_IPSUM, *args, **kwargs):
+ def __init__(self, paragraphs=7, max_length=None, text=LOREM_IPSUM, **kwargs):
+ super(LoremIpsum, self).__init__(**kwargs)
self.text = text
self.max_length = max_length
self.paragraphs = paragraphs
@@ -29,9 +43,6 @@ def __init__(self, paragraphs=7, max_length=None, text=LOREM_IPSUM, *args, **kwa
if self.paragraphs > len(self.text):
raise AttributeError('The Text %s only has %s paragraphs' %(text, len(text)))
- def __iter__(self):
- return self
-
def next(self):
text = u'\n\n'.join(self.text[:self.paragraphs])
if self.max_length:
@@ -39,27 +50,39 @@ def next(self):
return text
-class RandInt(object):
+class RandInt(Tube):
""" Generates a random integer between min and max """
- def __init__(self, min, max, *args, **kwargs):
+ def __init__(self, min, max, **kwargs):
+ super(RandInt, self).__init__(**kwargs)
self.min = min
self.max = max
- def __iter__(self):
- return self
-
def next(self):
return random.randint(self.min, self.max)
-class Contrib(object):
+class Contrib(Tube):
""" Crates a Custom Object. The backend class is the first parameter.
"""
- def __init__(self, backend, *args, **kwargs):
- self.backend = backend(*args, **kwargs)
+ def __init__(self, backend, **kwargs):
+ self.backend = backend(**kwargs)
def __iter__(self):
return self.backend
def next(self):
return self.backend.next()
+
+
+class AlwaysTrue(Tube):
+ """ Always returns True.
+ """
+ def next(self):
+ return True
+
+
+class AlwaysFalse(Tube):
+ """ Always returns False.
+ """
+ def next(self):
+ return False
View
BIN  scaffolding/__init__.pyc
Binary file not shown
View
BIN  scaffolding/contrib/__init__.pyc
Binary file not shown
View
33 scaffolding/contrib/facebook_graph.py
@@ -1,33 +0,0 @@
-""" This module still uses the master branch of the graph.
-"""
-from facebook.models import TestUser
-from facebook.testusers import TestUsers
-from facebook.utils import get_app_dict, get_static_graph
-
-
-class FacebookTestUser(object):
- def __init__(self, app_name=None, count=None, unique=True):
- self.app_name = app_name
- self.count = count
- self.unique = unique
-
- #application = get_app_dict(self.app_name)
- graph = get_static_graph(self.app_name)
- testusers = TestUsers(graph)
- self.users = testusers.get_test_users()
- if self.count and count > len(self.users):
- raise AttributeError('Not enough test users for app %s' % self.app_name)
- self.index = 0
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.index == len(self.users)-1:
- if self.unique:
- raise StopIteration
- else:
- self.index = 0
- return self.users[self.index]
- self.index += 1
- return self.users[self.index]
View
BIN  scaffolding/contrib/facebook_graph.pyc
Binary file not shown
View
0  scaffolding/contrib/__init__.py → scaffolding/external/__init__.py
File renamed without changes
View
70 scaffolding/external/facebook_graph.py
@@ -0,0 +1,70 @@
+""" This module still uses the master branch of the graph.
+"""
+from facebook.models import TestUser, User
+from facebook.testusers import TestUsers
+from facebook.utils import get_app_dict, get_static_graph
+from scaffolding import Tube
+
+
+class FacebookTestUser(Tube):
+ def __init__(self, app_name=None, unique=True, field_name=None, **kwargs):
+ super(FacebookTestUser, self).__init__(**kwargs)
+ self.app_name = app_name
+ self.unique = unique
+ self.field_name = field_name
+
+ self.graph = get_static_graph(self.app_name)
+ testusers = TestUsers(self.graph)
+ try:
+ print u'Checking for Facebook Test users...:\n'
+ except IOError:
+ pass
+ testuser_list = testusers.get_test_users()
+ try:
+ print u'Done. Found %s testusers.' % len(testuser_list)
+ except IOError:
+ pass
+ self.users = []
+
+ if unique:
+ if not field_name:
+ raise AttributeError('FacebookUser Fk unique defined but no field_name.')
+ # A fb user is unique to a cls instance.
+ # TODO: Write filter.
+
+ if self.count and self.count > len(testuser_list):
+ remaining = self.count-len(testuser_list)
+ try:
+ print 'Not enough Test users (%s). Generating %s more.\n' %(len(testuser_list), self.count)
+ except IOError:
+ pass
+ for i in range(remaining):
+ newuser = testusers.generate_new_test_user(installed=True, permissions=['email'])
+ try:
+ print u'Generated new Testuser: %s\n' % newuser
+ except IOError:
+ pass
+ # raise AttributeError('Not enough test users for app %s' % self.app_name)
+ testuser_list = testusers.get_test_users()
+
+ # The App wants Facebook Users, not Testusers.
+ for testuser in testuser_list:
+ user, created = User.objects.get_or_create(id=testuser.id)
+ if created:
+ user.get_from_facebook(self.graph, save=True)
+ self.users.append(user)
+
+ self.index = 0
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.index == len(self.users)-1:
+ if self.unique:
+ raise StopIteration
+ else:
+ self.index = 0
+ return self.users[self.index]
+ self.index += 1
+ return self.users[self.index]
View
BIN  scaffolding/library/__init__.pyc
Binary file not shown
View
BIN  scaffolding/library/lorem_ipsum.pyc
Binary file not shown
View
66 scaffolding/management/commands/scaffold.py
@@ -0,0 +1,66 @@
+#coding=utf-8
+from django.core.management.base import BaseCommand, CommandError
+from django.db import models
+from datetime import datetime
+from django.conf import settings
+import logging
+logger = logging.getLogger(__name__)
+
+class Command(BaseCommand):
+ args = '<app.model> <count>'
+ help = 'Creates placeholder data for your models.'
+
+ def handle(self, *args, **options):
+ if not args:
+ raise AttributeError('Do: scaffold <app_name> <count>')
+
+ import_path = args[0].split('.')
+
+ module = __import__('.'.join(import_path[:-1]), fromlist=[True])
+
+ model = getattr(module, import_path[-1])
+
+ if not isinstance(model, models.base.ModelBase):
+ raise AttributeError('%s is not a Django model.' % model)
+
+ count = int(args[1])
+
+ self.stdout.write(u'Creating %s\n' % model)
+
+ factory = self.make_factory(model, count)
+
+ for i in range(count):
+ self.make_object(model, factory)
+
+ self.stdout.write(u'\nCreated %s %ss\n' % (count, model))
+
+ def make_factory(self, cls, count):
+ """ Get the generators from the Scaffolding class within the model.
+ """
+ field_names = cls._meta.get_all_field_names()
+ fields = {}
+ text = u''
+ for field_name in field_names:
+ if hasattr(cls.Scaffolding, field_name):
+ generator, kwargs = getattr(cls.Scaffolding, field_name)
+ fields[field_name] = generator(count=count, cls=cls, **kwargs)
+ text += u'%s: %s; ' % (field_name, fields[field_name])
+ if hasattr(cls.Scaffolding, '%s_id' % field_name):
+ generator, kwargs = getattr(cls.Scaffolding, '%s_id' % field_name)
+ fields['%s_id' % field_name] = generator(count=count, cls=cls, **kwargs)
+ text += u'%s_id: %s; ' % (field_name, fields['%s_id' % field_name])
+
+ self.stdout.write(u'Generator for %s: %s\n' % (cls, text))
+
+ return fields
+
+ def make_object(self, cls, fields):
+ obj = cls()
+ self.stdout.write(u'\nCreated new %s: ' % obj)
+
+ for field_name, generator in fields.items():
+ value = generator.next()
+ setattr(obj, field_name, value)
+ self.stdout.write(u'%s: %s; ' % (field_name, value))
+
+ obj.save()

0 comments on commit b7f48d7

Please sign in to comment.
Something went wrong with that request. Please try again.