Examples

Examples

IOT lightbulb

Note

Full source located at iot_bulb.

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

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.