Convert python object to XML representation
The application I was working on used a Flash slide show. The configuration on the slide show was done from a xml file. The task was to make this configuration manageable from the Django admin.
I have created a model that represents the elements of the xml file. All I need was a way to convert the python database object to a xml representation.
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save, post_delete from lxml.etree import ElementTree, Element, SubElement import StringIO class XMLModelWriter: def __init__(self, model, file_name): self.model = model self.file_name = file_name def write(self): content_type = ContentType.objects.get_for_model(model=self.model) try: model_class = content_type.model_class() object_name = model_class._meta.object_name root = Element((object_name + 's').lower()) element_tree = ElementTree(root) for object in model_class.objects.all(): element = SubElement(root, object_name.lower()) for field in object._meta.fields: child = SubElement(element, field.name) value = getattr(object, field.name) if value != None: if isinstance(value, models.base.Model): # This field is a foreign key, so save the primary key # of the referring object pk_name = value._meta.pk.name pk_value = getattr(value, pk_name) child.text = unicode(pk_value) else: print value child.text = unicode(value) new_file = open(self.file_name, 'w') element_tree.write(new_file, pretty_print=True, xml_declaration=True, encoding='utf-8') except ContentType.DoesNotExist: pass class Item(models.Model): picture = models.CharField("Picture", blank=True, max_length=100) title = models.CharField("Title", blank=True, max_length=100) link = models.URLField("Link", verify_exists=False, blank=True) color = models.CharField("Color", blank=True, max_length=100) def __unicode__(self): return self.title class Meta: verbose_name = "Item" verbose_name_plural = "Items" def item_handler(sender, **kwargs): writer = XMLModelWriter(Item, 'D:/test/items.xml') writer.write() post_save.connect(item_handler, sender=Item) post_delete.connect(item_handler, sender=Item)
ContentType object is used to track all of the models installed, providing a high-level, generic interface for working with the models. Item objects are converted to a xml document, each time the user creates or modifies Item objects.
This code requires the lxml python library.



Tags: 



Leave a Reply