Exemplo n.º 1
0
    def test_role_set_operations(self):

        protected = whitelist('email', 'password')
        all_fields = whitelist('id', 'name') + protected

        def count(n):
            while True:
                yield n
                n += 1

        class User(Model):
            id = IntType(default=count(42).next)
            name = StringType()
            email = StringType()
            password = StringType()

            class Options:
                roles = {
                    'create': all_fields - ['id'],
                    'public': all_fields - ['password'],
                    'nospam': blacklist('password') + blacklist('email'),
                }

        data = {
            'id': 'NaN',
            'name': 'Arthur',
            'email': '*****@*****.**',
            'password': '******',
        }

        user = User({
            k: v
            for k, v in data.iteritems()
            if k in User._options.roles['create']  # filter by 'create' role
        })

        d = user.serialize(role='public')

        self.assertEqual(d, {
            'id': 42,
            'name': 'Arthur',
            'email': '*****@*****.**',
        })

        d = user.serialize(role='nospam')

        self.assertEqual(d, {
            'id': 42,
            'name': 'Arthur',
        })
Exemplo n.º 2
0
    def test_role_set_operations(self):

        protected = whitelist('email', 'password')
        all_fields = whitelist('id', 'name') + protected

        def count(n):
            while True:
                yield n
                n += 1

        class User(Model):
            id = IntType(default=count(42).next)
            name = StringType()
            email = StringType()
            password = StringType()

            class Options:
                roles = {
                    'create': all_fields - ['id'],
                    'public': all_fields - ['password'],
                    'nospam': blacklist('password') + blacklist('email'),
                }

        data = {
            'id': 'NaN',
            'name': 'Arthur',
            'email': '*****@*****.**',
            'password': '******',
        }

        user = User({
            k: v for k, v in data.iteritems()
            if k in User._options.roles['create']  # filter by 'create' role
        })

        d = user.serialize(role='public')

        self.assertEqual(d, {
            'id': 42,
            'name': 'Arthur',
            'email': '*****@*****.**',
        })

        d = user.serialize(role='nospam')

        self.assertEqual(d, {
            'id': 42,
            'name': 'Arthur',
        })
Exemplo n.º 3
0
def model_fields(model, only=None, exclude=None, hidden=None, field_args=None, converter=None):
  """
  Generate a dictionary of fields for a given Django model.

  See `model_form` docstring for description of parameters.
  """
  from schematics.models import Model
  if not isinstance(model, Model):
    raise TypeError('model must be a schematics.Model schema')

  converter = converter or ModelConverter()
  field_args = field_args or {}
  gottago = wholelist()
  field_dict = { }

  if only:
    gottago = whitelist(*only)
  elif exclude:
    gottago = blacklist(*exclude)

  for field_name, field in model._fields.items():
    if gottago(field_name, None): continue
    ishidden = False
    if hidden:
      if field_name in hidden: ishidden=True
      
    form_field = converter.convert(model, field, field_name, field_args.get(field_name), hidden=ishidden)
      
    if form_field is not None:
      field_dict[field_name] = form_field

  return field_dict
Exemplo n.º 4
0
def model_fields(model,
                 only=None,
                 exclude=None,
                 hidden=None,
                 field_args=None,
                 converter=None):
    """
    Generate a dictionary of fields for a given Django model.

    See `model_form` docstring for description of parameters.
    """
    from schematics.models import Model
    if not isinstance(model, Model):
        raise TypeError('model must be a schematics.Model schema')

    converter = converter or ModelConverter()
    field_args = field_args or {}
    gottago = wholelist()
    field_dict = {}

    if only:
        gottago = whitelist(*only)
    elif exclude:
        gottago = blacklist(*exclude)

    for field_name, field in model._fields.items():
        if gottago(field_name, None): continue
        ishidden = False
        if hidden:
            if field_name in hidden: ishidden = True

        form_field = converter.convert(model,
                                       field,
                                       field_name,
                                       field_args.get(field_name),
                                       hidden=ishidden)

        if form_field is not None:
            field_dict[field_name] = form_field

    from pprint import pprint
    #pprint(field_dict)
    return field_dict
Exemplo n.º 5
0
    def test_subclassing_overides_roles(self):
        class Parent(Model):
            id = StringType()
            gender = StringType()
            name = StringType()

            class Options:
                roles = {
                    'public': blacklist("id", "gender"),
                    'gender': blacklist("gender")
                }

        class GrandParent(Parent):
            age = IntType()
            family_secret = StringType()

            class Options:
                roles = {
                    'grandchildren': whitelist("age"),
                    'public': blacklist("id", "family_secret")
                }

        gramps = GrandParent({
            "id": "1",
            "name": "Edward",
            "gender": "Male",
            "age": 87,
            "family_secret": "Secretly Canadian"
        })

        options = gramps._options

        self.assertEqual(
            options.roles, {
                "grandchildren": whitelist("age"),
                "public": blacklist("id", "family_secret"),
                "gender": blacklist("gender")
            })
Exemplo n.º 6
0
    def test_subclassing_overides_roles(self):
        class Parent(Model):
            id = StringType()
            gender = StringType()
            name = StringType()

            class Options:
                roles = {
                    'public': blacklist("id", "gender"),
                    'gender': blacklist("gender")
                }

        class GrandParent(Parent):
            age = IntType()
            family_secret = StringType()

            class Options:
                roles = {
                    'grandchildren': whitelist("age"),
                    'public': blacklist("id", "family_secret")
                }

        gramps = GrandParent({
            "id": "1",
            "name": "Edward",
            "gender": "Male",
            "age": 87,
            "family_secret": "Secretly Canadian"
        })

        options = gramps._options

        self.assertEqual(options.roles, {
            "grandchildren": whitelist("age"),
            "public": blacklist("id", "family_secret"),
            "gender": blacklist("gender")
        })
Exemplo n.º 7
0
 class Options:
     serialize_when_none = False
     roles = {'public': whitelist('question_id', 'resources')}
Exemplo n.º 8
0
 class Options:
     serialize_when_none = False
     roles = {'public': whitelist('name')}
Exemplo n.º 9
0
 class Options:
     roles = {
         'owner': wholelist(),
         'public': whitelist('name', 'bio'),
     }
Exemplo n.º 10
0
 class Options:
     roles = {"public": whitelist("total_wins", "total_losses")}
Exemplo n.º 11
0
 class Options:
     roles = {
         'owner': blacklist(),
         'public': whitelist('title', 'year'),
     }
Exemplo n.º 12
0
 class Options:
     roles = {
         'grandchildren': whitelist("age"),
         'public': blacklist("id", "family_secret")
     }
Exemplo n.º 13
0
 class Options:
     serialize_when_none = False
     roles = {
         "public": whitelist("id"),
     }
Exemplo n.º 14
0
 class Options:
     roles = {
         'owner': blacklist('personal_thoughts'),
         'public': whitelist('author', 'content', 'comments'),
     }
Exemplo n.º 15
0
 class Options:
     roles = {
         'owner': wholelist(),
         'public': whitelist('username', 'text'),
     }
Exemplo n.º 16
0
 class Options:
     roles = {
         'owner': blacklist('is_active'),
         'public': whitelist('username', 'name'),
     }
Exemplo n.º 17
0
 class Options:
     roles = {
         'meow': blacklist('owner'),
         'woof': whitelist('id'),
     }
Exemplo n.º 18
0
 class Options:
     roles = {'public': whitelist('city')}
Exemplo n.º 19
0
 class Options:
     roles = {'public': whitelist('name')}
Exemplo n.º 20
0
 class Options:
     roles = {
         'public': whitelist('name', 'bio'),
     }
Exemplo n.º 21
0
    class Options:
        roles = {
            'owner': blacklist(),
            'public': whitelist('title', 'year'),
        }


mv = Movie()
mv.title = 'Total Recall'
mv.year = 1990
mv.personal_thoughts = 'I wish I had three hands...'

print 'From Movie class to json string:\n\n    %s\n' % (to_json(mv))
print '    %s\n' % (to_python(mv, allow_none=True))
print '    %s\n' % (to_json(mv, allow_none=True))

###
### Scrubbing functions
###

ownersafe_json = make_safe_json(Movie, mv, 'owner')
ownersafe_str = 'Making mv safe:\n\n    %s\n'
print ownersafe_str % (ownersafe_json)

publicsafe_json = make_safe_json(Movie, mv, 'public')
publicsafe_str = 'Making mv safe in json:\n\n    %s\n'
print publicsafe_str % (publicsafe_json)

print 'You can also scrub the models according to whatever system you want:\n'
print '    %s\n' % (to_json(mv, gottago=whitelist('title')))
Exemplo n.º 22
0
    class Options:
        roles = {
            'owner': blacklist(),
            'public': whitelist('title', 'year'),
        }

mv = Movie()
mv.title = 'Total Recall'
mv.year = 1990
mv.personal_thoughts = 'I wish I had three hands...'

print 'From Movie class to json string:\n\n    %s\n' % (to_json(mv))
print '    %s\n' % (to_python(mv, allow_none=True))
print '    %s\n' % (to_json(mv, allow_none=True))


###
### Scrubbing functions
###

ownersafe_json = make_safe_json(Movie, mv, 'owner')
ownersafe_str = 'Making mv safe:\n\n    %s\n'
print ownersafe_str % (ownersafe_json)

publicsafe_json = make_safe_json(Movie, mv, 'public')
publicsafe_str = 'Making mv safe in json:\n\n    %s\n'
print  publicsafe_str % (publicsafe_json)

print 'You can also scrub the models according to whatever system you want:\n'
print '    %s\n' % (to_json(mv, gottago=whitelist('title')))