def test_dict_to_xml(self): params = {"123": "123"} sign = '1234567890' result = dict_to_xml(params, sign) expect_result = "<xml><123>123</123><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = {"123": "xyz123"} result = dict_to_xml(params, sign) expect_result = "<xml><123><![CDATA[xyz123]]></123><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = { "123": "123", "abc": "abc", } result = dict_to_xml(params, sign) expect_result = "<xml><123>123</123><abc><![CDATA[abc]]></abc><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = { "c": "123", "a": "abc", } result = dict_to_xml(params, sign) expect_result = "<xml><a><![CDATA[abc]]></a><c>123</c><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result)
def catalog_xml(catalog): c = models.select_catalog(catalog) if c is not None: return utils.xml_response(utils.dict_to_xml('catalog', c.serialize), 200) else: abort(404)
def request(self, xml=None, type=None): if not self.session_id and type != RequestType.login: self.connect() if xml: xml = utils.dict_to_xml({'message': xml}) post_data = {'xml': xml} if type is RequestType.login: url = self.authentication.format(self._username, self._password) elif type is RequestType.batch_message: raise NotImplementedError() elif type is RequestType.single_message: url = self.send_single_sms.format(self.session_id) elif type is RequestType.routes: url = self.routes_url.format(self.session_id) else: raise Exception('Invalid RequestType') req_headers = { 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)' } if xml: r = requests.post(url, data=post_data, headers=req_headers) else: r = requests.get(url, headers=req_headers) return r.text
def item_xml(id): item = models.select_item_by_id(id) if item is not None: return utils.xml_response(utils.dict_to_xml('item', item.serialize), 200) else: abort(404)
def request(self, xml=None, type=None): if not self.session_id and type != RequestType.login: self.connect() if xml: xml = utils.dict_to_xml({'message': xml}) post_data = {'xml': xml} if type is RequestType.login: url = self.authentication.format(self._username, self._password) elif type is RequestType.batch_message: raise NotImplementedError() elif type is RequestType.single_message: url = self.send_single_sms.format(self.session_id) elif type is RequestType.routes: url = self.routes_url.format(self.session_id) else: raise Exception('Invalid RequestType') req_headers = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)'} if self.proxy is True: url = 'http://youtubeproxy.org/default.aspx?prx={0}'.format(url) if xml: r = requests.post(url, data=post_data, headers=req_headers) else: r = requests.get(url, headers=req_headers) return r.text
def post_xml(self): sign = calculate_sign(self.params, self.api_key) xml = dict_to_xml(self.params, sign) print xml response = post_xml(self.url, xml) print '*' * 5, response.text return xml_to_dict(response.text)
def catalogs_xml(): ''' Convert list of unserializable object to xml: 1. Retrive data 2. Turn each object to xml 3. Wrap them with a xml tag ''' return utils.xml_response(utils.list_to_xml('catalogs', [ utils.dict_to_xml('catalog', x.serialize) for x in models.select_catalogs_all() ]), 200)
def to_xml(self): extra = dict(id=self.key().id(), cityId=self.cityRef.key().id(), creationDateTime=unicode(self.updateDateTime.isoformat()+ "Z"), updateDateTime=unicode(self.updateDateTime.isoformat() + "Z"), locationsUpdated=unicode(self.locationsUpdated.isoformat() + "Z")) provider = obj2dict(self, self.properties(), exclude=['cityRef'], extra=extra) provider = dict_to_xml(provider, "provider") return provider
def to_xml(self): extra = dict(id=self.key().id(), latitude=self.geoloc.lat, longitude=self.geoloc.lon, creationDateTime=unicode(self.updateDateTime.isoformat()+ "Z"), updateDateTime=unicode(self.updateDateTime.isoformat() + "Z")) city = obj2dict(self, self.properties(), exclude=['geoloc'], extra= extra) city = dict_to_xml(city, "city") return city
def to_xml(self): extra = dict(id=self.key().id(), stationRef=self.stationRef.key().id(), cityId=self.city.key().id(), stationId=self.stationRef.key().id(), creationDateTime=unicode(self.updateDateTime.isoformat()+ "Z"), updateDateTime=unicode(self.updateDateTime.isoformat() + "Z")) station = obj2dict(self, self.properties(), exclude=['stationRef', 'geoloc'], extra=extra) station = dict_to_xml(station, "stationStatus") #stationStatuses return station
def to_xml(self): extra = dict(id=self.key().id(), latitude=self.geoloc.lat, longitude=self.geoloc.lon, providerId=self.providerRef.key().id(), cityId=self.providerRef.cityRef.key().id(), creationDateTime=unicode(self.updateDateTime.isoformat()+ "Z"), updateDateTime=unicode(self.updateDateTime.isoformat() + "Z")) station = obj2dict(self, self.properties(), exclude=['providerRef', 'geoloc'], extra=extra) station = dict_to_xml(station, "station") return station
def catalogs_xml(): ''' Convert list of unserializable object to xml: 1. Retrive data 2. Turn each object to xml 3. Wrap them with a xml tag ''' return utils.xml_response( utils.list_to_xml('catalogs', [ utils.dict_to_xml('catalog', x.serialize) for x in models.select_catalogs_all() ]), 200)
def test_dict_to_xml(self): params = {"123": "123"} sign = "1234567890" result = dict_to_xml(params, sign) expect_result = "<xml><123>123</123><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = {"123": "xyz123"} result = dict_to_xml(params, sign) expect_result = "<xml><123><![CDATA[xyz123]]></123><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = {"123": "123", "abc": "abc"} result = dict_to_xml(params, sign) expect_result = "<xml><123>123</123><abc><![CDATA[abc]]></abc><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result) params = {"c": "123", "a": "abc"} result = dict_to_xml(params, sign) expect_result = "<xml><a><![CDATA[abc]]></a><c>123</c><sign><![CDATA[%s]]></sign></xml>" % sign self.assertEqual(result, expect_result)
def get(self): self.set_header('Content-Type','text/xml') db = self.db d = load_info(db).copy() site_url = d['site_url'] rss_size = utils.get_int(d.get('rss_size', ''), 10) items = [] last_update = None if rss_size > 0: postIds = db.query(Post.id).\ filter(Post.ispass == True).\ order_by( Post.id.desc() )[0:rss_size] postIds = (x[0] for x in postIds) posts = db.query(Post).\ filter(Post.id.in_(postIds)).\ all() for post in posts: items.append({ 'title':post.title, 'link': utils.urlwrite(site_url, post.url), 'pubDate': post.\ pubdate.strftime('%a, %d %b %Y %H:%M:%S GMT'), 'dc:creator': post.user.nickname, 'guid':{ '_text': utils.urlwrite(site_url, post.url), '__isPermaLink': 'true' }, 'content:encoded': post.content }) if posts and len(posts) > 0: last_update = posts[0].\ pubdate.strftime('%a, %d %b %Y %H:%M:%S GMT') xmldict = {'rss': { '__version':'2.0', '__xmlns:content': 'http://purl.org/rss/1.0/modules/content/', '__xmlns:wfw': 'http://wellformedweb.org/CommentAPI/', '__xmlns:dc': 'http://purl.org/dc/elements/1.1/', 'channel': { 'title': d['site_name'], 'link': d['site_url'], 'description': d['site_description'], 'pubDate': last_update, 'language': 'zh-CN', 'item': items# end item }# end channel }} return self.finish(utils.dict_to_xml(xmldict))
def main(): with manager.connect(**constants.NC_CONN_PARAMS) as nc, open( "netconf_cfg/provision.yml") as f: yaml = YAML(typ="safe") data = yaml.load(f) xml = utils.dict_to_xml(data, root="config") print(f"Sending RPC:\n{P(xml)}") xml_str = etree.tostring(xml).decode("utf-8") nc_reply = nc.edit_config(xml_str, target="running") print(f"Received RPC reply:\n{P(nc_reply.xml)}") print("Saving configuration") nc_reply = nc.dispatch(xml_.to_ele(constants.NC_SAVE_CONFIG_RPC)) if nc_reply.ok: print("Running config was saved to startup successfully") else: print("Failed to save running config to startup")
def main(): with manager.connect( host=constants.NC_HOST, port=constants.NC_PORT, username=constants.DEVICE_USERNAME, password=constants.DEVICE_PASSWORD, timeout=30, hostkey_verify=False, ) as nc, open("netconf_cfg/provision.yml") as f: yaml = YAML(typ="safe") data = yaml.load(f) xml = utils.dict_to_xml(data, root="config") print(f"Sending RPC:\n{P(xml)}") xml_str = etree.tostring(xml).decode('utf-8') nc_reply = nc.edit_config(xml_str, target="running") print(f"Received RPC reply:\n{P(nc_reply.xml)}") print("Saving configuration") nc_reply = nc.dispatch(xml_.to_ele(constants.NC_SAVE_CONFIG_RPC)) if nc_reply.ok: print("Running config was saved to startup successfully") else: print("Failed to save running config to startup")
def items_xml(): return utils.xml_response(utils.list_to_xml('items', [ utils.dict_to_xml('item', x.serialize) for x in models.select_items_all() ]), 200)
''' test di utils.py - dict_to_xmlDOC import utils import xml.dom.minidom a = {"a": 12, "b" : {"C":4,"D":'asda'}} doc = xml.dom.minidom.Document() c = doc.createElement('test') utils.dict_to_xml(a,doc,c) doc.appendChild(c) fine test ''' import utils import xml.etree.ElementTree as ET a = {"a": 12, "b" : {"C":4,"D":'asda'}} ''' >>> a = ET.Element('a') >>> b = ET.SubElement(a, 'b') >>> c = ET.SubElement(a, 'c') >>> d = ET.SubElement(c, 'd') >>> ET.dump(a) <a><b /><c><d /></c></a> ''' doc = ET.Element('test') utils.dict_to_xml(a,doc) ET.dump(doc) tree = ET.ElementTree(doc) tree.write('test.xml') tree = ET.parse('test.xml') root = tree.getroot() a = root.find('a') print a.text , " e' il testo di a"
def post_xml(self): sign = calculate_sign(self.params, self.api_key) xml = dict_to_xml(self.params, sign) response = post_xml(self.url, xml) return xml_to_dict(response.text)
def items_xml(): return utils.xml_response( utils.list_to_xml('items', [ utils.dict_to_xml('item', x.serialize) for x in models.select_items_all() ]), 200)