This will most likely be useful to you if you’re doing web applications (web services or web APIs) but the idea would still be applicable for other use cases.
Since there’s really no standard way of rendering data, we usually have to support multiple format. In this blog, we’ll cover the most common formats in XML and JSON, then later see how we can support custom data types.
Version 1: Engine Based
Engine-based means the logic for parsing data is written in the engine, normally this would be the web application itself.
Typical example would be returning data from a database or object in a serialized form (eg XML, JSON).
Data Definition
For this demo, we’ll just define a dictionary. But this will be a special dictionary as it MUST contain a single-top-node. Why? Cause the module we’ll use to convert this to xml requires that 🙂
Modules Used
To serialize data, we’ll use readily-available Python modules.
json
This module converts an object to a JSON-formatted string. It is built-in module in Python 3 so nothing extra to do other than import it.
xmltodict
This module converts an object to an XML-formatted string. This module needs to be installed via pip.
Engine
Our engine in this demo is a class that has a render method. It accepts data and format parameters
The most common way of doing it is this:
If you’re advanced, you might write it like this:
To use the engine, you just instantiate it and invoke its render method:
Nothing special here, it will output the data as expected:
Engine Implementation Summary
The number of data formats that can be supported depends on the engine. This means, in order to support new data formats, the Engine has to know how to do it.
Of course you could use the Advanced implementation and keep adding new renderers. But the point is, all these rendering logic exists on the Engine side. What if the data source is from another system that you don’t own or manage? And if this other system uses a different data type, how would you do it on your end?
In part 2, we’ll explore this question and find an alternative way of doing it.