Note
Full source located at iot_bulb.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
from datetime import datetime
from oslo_versionedobjects import base
from oslo_versionedobjects import fields as obj_fields
# INTRO: This example shows how a object (a plain-old-python-object) with
# some associated fields can be used, and some of its built-in methods can
# be used to convert that object into a primitive and back again (as well
# as determine simple changes on it.
# Ensure that we always register our object with an object registry,
# so that it can be deserialized from its primitive form.
@base.VersionedObjectRegistry.register
class IOTLightbulb(base.VersionedObject):
"""Simple light bulb class with some data about it."""
VERSION = '1.0' # Initial version
#: Namespace these examples will use.
OBJ_PROJECT_NAMESPACE = 'versionedobjects.examples'
#: Required fields this object **must** declare.
fields = {
'serial': obj_fields.StringField(),
'manufactured_on': obj_fields.DateTimeField(),
}
# Now do some basic operations on a light bulb.
bulb = IOTLightbulb(serial='abc-123', manufactured_on=datetime.now())
print("The __str__() output of this new object: %s" % bulb)
print("The 'serial' field of the object: %s" % bulb.serial)
bulb_prim = bulb.obj_to_primitive()
print("Primitive representation of this object: %s" % bulb_prim)
# Now convert the primitive back to an object (isn't it easy!)
bulb = IOTLightbulb.obj_from_primitive(bulb_prim)
bulb.obj_reset_changes()
print("The __str__() output of this new (reconstructed)"
" object: %s" % bulb)
# Mutating a field and showing what changed.
bulb.serial = 'abc-124'
print("After serial number change, the set of fields that"
" have been mutated is: %s" % bulb.obj_what_changed())
|
Expected (or similar) output:
The __str__() output of this new object: IOTLightbulb(manufactured_on=2017-03-15T23:25:01Z,serial='abc-123')
The 'serial' field of the object: abc-123
Primitive representation of this object: {'versioned_object.version': '1.0', 'versioned_object.changes': ['serial', 'manufactured_on'], 'versioned_object.name': 'IOTLightbulb', 'versioned_object.data': {'serial': u'abc-123', 'manufactured_on': '2017-03-15T23:25:01Z'}, 'versioned_object.namespace': 'versionedobjects.examples'}
The __str__() output of this new (reconstructed) object: IOTLightbulb(manufactured_on=2017-03-15T23:25:01Z,serial='abc-123')
After serial number change, the set of fields that have been mutated is: set(['serial'])
Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.