Пример #1
0
    def _make_presentable(self, datum):
        """This function takes either a model instance or a dictionary
        representation of some model and returns a dictionary one safe for
        transmitting as payload.
        """
        if isinstance(datum, dict):
            iid = str(datum.get('id'))
            model_instance = self.model(**datum)
            instance = to_json(model_instance, encode=False)
        else:
            iid = str(datum.id)
            instance = to_json(datum, encode=False)

        data = make_safe_json(self.model, instance, 'owner', encode=False)

        return data
Пример #2
0
    def _make_presentable(self, datum):
        """This function takes either a model instance or a dictionary
        representation of some model and returns a dictionary one safe for
        transmitting as payload.
        """
        if isinstance(datum, dict):
            iid = str(datum.get('id'))
            model_instance = self.model(**datum)
            instance = to_json(model_instance, encode=False)
        else:
            iid = str(datum.id)
            instance = to_json(datum, encode=False)

        data = make_safe_json(self.model, instance, 'owner', encode=False)

        return data
Пример #3
0
 def save(self, obj, role=None):
     if obj.validate():
         filename = self.file_name(obj.type_slug, str(obj.slug))
         print filename
         f = open(self.file_name(obj.type_slug, str(obj.slug)), 'w')
         f.write(to_json(obj))
         f.close()
         return True
     else:
         return False
Пример #4
0
    """
    actions = ListType(ModelType(Action))
    created_date = DateTimeType(default=datetime.datetime.now)
    updated_date = DateTimeType(default=datetime.datetime.now)
    num_completed = IntType(default=0)


###
### Actions
###

a1 = Action(value='Hello Mike', tags=['Erlang', 'Mike Williams'])
a2 = Action(value='Hello Joe', tags=['Erlang', 'Joe Armstrong'])

print 'Action 1 as Python:\n\n    %s\n' % (to_python(a1))
print 'Action 2 as JSON:\n\n    %s\n' % (to_json(a2))

###
### SingleTask
###

st = SingleTask()
st.action = a1

print 'Single task as Python:\n\n    %s\n' % (to_python(st))
print 'Single task as JSON:\n\n    %s\n' % (to_json(st))

###
### TaskList
###
Пример #5
0
 def setUp(self):
     self.instance = self.klass(**self.description)
     self.as_python = to_python(self.instance)
     self.as_json = to_json(self.instance, sort_keys=True)
     self.json_owner_safe = json.dumps(self.owner_safe, sort_keys=True)
     self.json_public_safe = json.dumps(self.public_safe, sort_keys=True)
Пример #6
0
customer = Customer(username="******",
                    email="*****@*****.**",
                    first_name="Ben",
                    last_name="G",
                    date_made=datetime.datetime.utcnow(),
                    orders=[order])

###
### Serialization
###

### Serialize to Python
print 'Customer as Python:\n\n    %s\n' % (to_python(customer))

### Serialize to JSON
print 'Customer as JSON:\n\n    %s\n' % (to_json(customer))

### Serialize data to JSON and load back into Python dictionary.
print 'Serializing model to JSON and loading into new instance...\n'
json_data = to_json(customer)
customer_dict = json.loads(json_data)

### Instantiate customer instance from pythonified JSON data
loaded_customer = Customer(**customer_dict)

### Reserialize to Python
print 'Customer as Python:\n\n    %s\n' % (to_python(loaded_customer))

### Reserialize to JSON
print 'Customer as JSON:\n\n    %s\n' % (to_json(loaded_customer))
Пример #7
0
    def set_password(self, plaintext):
        hash_string = hashlib.md5(plaintext).hexdigest()
        self.secret = hash_string


###
### Manually create an instance
###

### Create instance with bogus password
u = User()
u.secret = 'whatevz'
u.name = 'test hash'

### Validation will fail because u.secret does not contain an MD5 hash
print 'Attempting validation on:\n\n    %s\n' % (to_json(u))
try:
    validate_instance(u)
    print 'Validation passed\n'
except TypeException, se:
    print 'TypeException caught: %s\n' % (se)

### Set the password *correctly* using our `set_password` function
u.set_password('whatevz')
print 'Adjusted invalid data and trying again on:\n\n    %s\n' % (to_json(u))
try:
    validate_instance(u)
    print 'Validation passed\n'
except TypeException, se:
    print 'TypeException caught: %s (This section wont actually run)\n' % (se)
Пример #8
0
        roles = {
            'owner': blacklist(),
            'public': whitelist('title', 'year'),
        }
        


m = Movie(title='Some Movie',
          year=2011,
          personal_thoughts='It was pretty good')


print 'MOVIE ]', ('-' * 40)
print '    schema ::', to_jsonschema(m)
print '    python ::', to_python(m)
print '      json ::', to_json(m)
print '     owner ::', make_safe_python(Movie, m, 'owner')
print '    public ::', make_safe_json(Movie, m, 'public')
print


#movie_json = m.to_json()
movie_json = make_safe_json(Movie, m, 'owner')
print 'Movie as JSON ]', ('-' * 32)
print '      json ::', movie_json
print


### Reload movie
movie_data = json.loads(movie_json)
m2 = Movie(**movie_data)
Пример #9
0
 def for_json(self, value):
     return to_json(value, encode=False)
Пример #10
0
class Media(Model):
    """Simple document that has one StringField member
    """
    id = UUIDType(auto_fill=True)
    owner = UUIDType()
    title = StringType(max_length=40)


make_believe_owner_id = uuid.uuid4()

m = Media()
m.owner = make_believe_owner_id
m.title = 'Misc Media'

print 'From Media class to json string:\n\n    %s\n' % (to_json(m))

###
### Subclass `Media` to create a `Movie`
###


class Movie(Media):
    """Subclass of Foo. Adds bar and limits publicly shareable
    fields to only 'bar'.
    """
    year = IntType(min_value=1950, max_value=datetime.datetime.now().year)
    personal_thoughts = StringType(max_length=255)

    class Options:
        roles = {
Пример #11
0
    class Options:
        roles = {
            'owner': blacklist(),
            'public': whitelist('title', 'year'),
        }


m = Movie(title='Some Movie',
          year=2011,
          personal_thoughts='It was pretty good')

print 'MOVIE ]', ('-' * 40)
print '    schema ::', to_jsonschema(m)
print '    python ::', to_python(m)
print '      json ::', to_json(m)
print '     owner ::', make_safe_python(Movie, m, 'owner')
print '    public ::', make_safe_json(Movie, m, 'public')
print

#movie_json = m.to_json()
movie_json = make_safe_json(Movie, m, 'owner')
print 'Movie as JSON ]', ('-' * 32)
print '      json ::', movie_json
print

### Reload movie
movie_data = json.loads(movie_json)
m2 = Movie(**movie_data)

print 'RESTORED MOVIE ]', ('-' * 31)
 def setUp(self):
     self.instance = self.klass(**self.description)
     self.as_python = to_python(self.instance)
     self.as_json = to_json(self.instance, sort_keys=True)
     self.json_owner_safe = json.dumps(self.owner_safe, sort_keys=True)
     self.json_public_safe = json.dumps(self.public_safe, sort_keys=True)
Пример #13
0
    def set_password(self, plaintext):
        hash_string = hashlib.md5(plaintext).hexdigest()
        self.secret = hash_string


###
### Manually create an instance
###

### Create instance with bogus password
u = User()
u.secret = 'whatevz'
u.name = 'test hash'

### Validation will fail because u.secret does not contain an MD5 hash
print 'Attempting validation on:\n\n    %s\n' % (to_json(u))
try:
    validate_instance(u)
    print 'Validation passed\n'
except TypeException, se:
    print 'TypeException caught: %s\n' % (se)
    

### Set the password *correctly* using our `set_password` function
u.set_password('whatevz')
print 'Adjusted invalid data and trying again on:\n\n    %s\n' % (to_json(u))
try:
    validate_instance(u)
    print 'Validation passed\n'
except TypeException, se:
    print 'TypeException caught: %s (This section wont actually run)\n' % (se)
Пример #14
0
customer = Customer(username="******",
                    email="*****@*****.**",
                    first_name="Ben",
                    last_name="G",
                    date_made=datetime.datetime.utcnow(),                    
                    orders=[order])

###
### Serialization
###

### Serialize to Python
print 'Customer as Python:\n\n    %s\n' % (to_python(customer))

### Serialize to JSON
print 'Customer as JSON:\n\n    %s\n' % (to_json(customer))

### Serialize data to JSON and load back into Python dictionary.
print 'Serializing model to JSON and loading into new instance...\n'
json_data = to_json(customer)
customer_dict = json.loads(json_data)

### Instantiate customer instance from pythonified JSON data
loaded_customer = Customer(**customer_dict)

### Reserialize to Python
print 'Customer as Python:\n\n    %s\n' % (to_python(loaded_customer))

### Reserialize to JSON
print 'Customer as JSON:\n\n    %s\n' % (to_json(loaded_customer))
Пример #15
0
    """
    actions = ListType(ModelType(Action))
    created_date = DateTimeType(default=datetime.datetime.now)
    updated_date = DateTimeType(default=datetime.datetime.now)
    num_completed = IntType(default=0)


###
### Actions
###

a1 = Action(value='Hello Mike', tags=['Erlang', 'Mike Williams'])
a2 = Action(value='Hello Joe', tags=['Erlang', 'Joe Armstrong'])

print 'Action 1 as Python:\n\n    %s\n' % (to_python(a1))
print 'Action 2 as JSON:\n\n    %s\n' % (to_json(a2))


###
### SingleTask
###

st = SingleTask()
st.action = a1

print 'Single task as Python:\n\n    %s\n' % (to_python(st))
print 'Single task as JSON:\n\n    %s\n' % (to_json(st))


###
### TaskList
Пример #16
0
 def for_json(self, value):
     return to_json(value, encode=False)
Пример #17
0
###

class Media(Model):
    """Simple document that has one StringField member
    """
    id = UUIDType(auto_fill=True)
    owner = UUIDType()
    title = StringType(max_length=40)

make_believe_owner_id = uuid.uuid4()

m = Media()
m.owner = make_believe_owner_id
m.title = 'Misc Media'

print 'From Media class to json string:\n\n    %s\n' % (to_json(m))


###
### Subclass `Media` to create a `Movie`
###

class Movie(Media):
    """Subclass of Foo. Adds bar and limits publicly shareable
    fields to only 'bar'.
    """
    year = IntType(min_value=1950, max_value=datetime.datetime.now().year)
    personal_thoughts = StringType(max_length=255)
    class Options:
        roles = {
            'owner': blacklist(),