comparison sat/memory/params.py @ 3105:eec0c25c796b

core (memory/params): new "makeOptions" method to easily create options XML from a dict
author Goffi <goffi@goffi.org>
date Fri, 03 Jan 2020 13:20:45 +0100
parents fee60f17ebac
children 0c29155ac68b
comparison
equal deleted inserted replaced
3104:118d91c932a7 3105:eec0c25c796b
29 from twisted.internet import defer 29 from twisted.internet import defer
30 from twisted.python.failure import Failure 30 from twisted.python.failure import Failure
31 from twisted.words.xish import domish 31 from twisted.words.xish import domish
32 from twisted.words.protocols.jabber import jid 32 from twisted.words.protocols.jabber import jid
33 from sat.tools.xml_tools import paramsXML2XMLUI, getText 33 from sat.tools.xml_tools import paramsXML2XMLUI, getText
34 from xml.sax.saxutils import quoteattr
34 35
35 # TODO: params should be rewritten using Twisted directly instead of minidom 36 # TODO: params should be rewritten using Twisted directly instead of minidom
36 # general params should be linked to sat.conf and kept synchronised 37 # general params should be linked to sat.conf and kept synchronised
37 # this need an overall simplification to make maintenance easier 38 # this need an overall simplification to make maintenance easier
38 39
1130 @return: True if this node concerns the given app. 1131 @return: True if this node concerns the given app.
1131 """ 1132 """
1132 if not app or not node.hasAttribute("app"): 1133 if not app or not node.hasAttribute("app"):
1133 return True 1134 return True
1134 return node.getAttribute("app") == app 1135 return node.getAttribute("app") == app
1136
1137
1138 def makeOptions(options, selected=None):
1139 """Create option XML form dictionary
1140
1141 @param options(dict): option's name => option's label map
1142 @param selected(None, str): value of selected option
1143 None to use first value
1144 @return (str): XML to use in parameters
1145 """
1146 str_list = []
1147 if selected is None:
1148 selected = next(iter(options.keys()))
1149 selected_found = False
1150 for value, label in options.items():
1151 if value == selected:
1152 selected = 'selected="true"'
1153 selected_found = True
1154 else:
1155 selected = ''
1156 str_list.append(
1157 f'<option value={quoteattr(value)} label={quoteattr(label)} {selected}/>'
1158 )
1159 if not selected_found:
1160 raise ValueError(f"selected value ({selected}) not found in options")
1161 return '\n'.join(str_list)