I would like to generate specific xml strings from my module, based on the type of msg requested by some code using my module. Each of these xml strings contains some data that gets generated dynamically. For example, many of these xml string have a cookie field that is generated using another function.
I started out with a python dictionary that initializes all the xml strings with the dynamic field (ie cookie) pre-populated (ie, not exactly dynamic). And then I call the dictionary to get the relevant xml strings.
The problem with this approach is that the cookies expire every hour and therefore the strings being returned by the module after an hour have those expired values. What I would ideally like to have is some form of a generator function (not sure if that’s even possible in this case) that returns the correctly formed strings as and when they are requested based on the msg_type requested (as in the example below). Each of the xml strings saved in this dict is in a unique format, so I can’t exactly have some sort of a common template xml generator.
As an example, the dict that I have defined looks similar to get_msg dictionary here:
get_msg["msg_value_1"] = """<ABC cookie=""" + getCookie() + """ >
<XYZ """ + foo_name +""">
</XYZ>
</ABC>"""
get_msg["msg_value_2"] = """<ABC cookie=""" + getCookie() + """ >
<some text """ + bar_name + """>
</XYZ>
</ABC>"""
What would be a good approach to be able to generate these xml strings on the fly with getCookie() getting invoked for every fresh msg request (not necessarily using dictionaries). Any input would be appreciated.
For this I would create a class that is as such
This will allow you to pass in various templates and each part that you need to replace you will have
{cookie}with the name wrapped with curly brackets. TheseSFobjects can then be stored into your dictionary and then simply called to returned your respective XML.I also highly recommend using a XML library such as
lxmlor something similar to produce correct XML when things get more complicated.