Examples¶
IOT lightbulb¶
Note
Full source located at https://opendev.org/openstack/oslo.versionedobjects/oslo_versionedobjects/examples/iot_bulb.py.
1
2from oslo_versionedobjects import base
3from oslo_versionedobjects import fields as obj_fields
4
5# INTRO: This example shows how a object (a plain-old-python-object) with
6# some associated fields can be used, and some of its built-in methods can
7# be used to convert that object into a primitive and back again (as well
8# as determine simple changes on it.
9
10
11# Ensure that we always register our object with an object registry,
12# so that it can be deserialized from its primitive form.
13@base.VersionedObjectRegistry.register
14class IOTLightbulb(base.VersionedObject):
15 """Simple light bulb class with some data about it."""
16
17 VERSION = '1.0' # Initial version
18
19 #: Namespace these examples will use.
20 OBJ_PROJECT_NAMESPACE = 'versionedobjects.examples'
21
22 #: Required fields this object **must** declare.
23 fields = {
24 'serial': obj_fields.StringField(),
25 'manufactured_on': obj_fields.DateTimeField(),
26 }
27
28
29# Now do some basic operations on a light bulb.
30bulb = IOTLightbulb(serial='abc-123', manufactured_on=datetime.now())
31print("The __str__() output of this new object: %s" % bulb)
32print("The 'serial' field of the object: %s" % bulb.serial)
33bulb_prim = bulb.obj_to_primitive()
34print("Primitive representation of this object: %s" % bulb_prim)
35
36# Now convert the primitive back to an object (isn't it easy!)
37bulb = IOTLightbulb.obj_from_primitive(bulb_prim)
38
39bulb.obj_reset_changes()
40print("The __str__() output of this new (reconstructed)"
41 " object: %s" % bulb)
42
43# Mutating a field and showing what changed.
44bulb.serial = 'abc-124'
45print("After serial number change, the set of fields that"
46 " 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'])