Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. from mongoengine import *
  2.  
  3. class UpdatableDocument(Document):
  4.  
  5. schema_version = IntField(default=0)
  6.  
  7. schema_updates = {} # Dictionary to hold all the updates
  8.  
  9. def __init__(self, *args, **kwargs):
  10. values = self.schema_update(kwargs)
  11. super().__init__(*args, **values)
  12.  
  13. def schema_update(values):
  14. version = values.get('schema_version', 0)
  15. next_version = version + 1
  16.  
  17. # Get the n+1 version and perform the delta
  18. # keep doing until there are no new versions
  19. while self.schema_updates.get(next_version):
  20. update = self.schema_updates[next_version]
  21. update(values)
  22. values['schema_version'] = next_version
  23. next_version += 1
  24.  
  25. return values
  26.  
  27. class IoTProduct(Document):
  28. """ Information about all devices of a specific type """
  29. tags = ListField(StringField())
  30. field_d = IntField()
  31.  
  32.  
  33. def schema_update_add_product_tags(values):
  34. """Adds the tags from the products to the tags field on the device
  35.  
  36. Args:
  37. values (dict): A dictionary loaded from the mongodb BSON.
  38. Returns: None
  39. """
  40. product = IoTProduct.objects.get(id=values['field_c'].id)
  41. values['tags'] = product.tags
  42.  
  43. class IoTDevice(UpdatableDocument):
  44. """ Information about a specific IoT device """
  45. field_a = StringField()
  46. field_b = IntField()
  47. field_c = ReferenceField(IoTProduct)
  48. tags = ListField(StringField())
  49.  
  50. schema_updates = {
  51. 1: schema_update_add_product_tags,
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement