我有一个要实例化的类,然后将其传递给 Tornado Web 模板。这两个函数都返回一个列表,但我在使类本身成为可迭代对象时遗漏了一些东西。恐怕这是我做错了根本的事情。我正在进行 REST API 调用,解析返回的 XML 并将一些数据返回到 webapp。这是代码:
API 调用:
class GetVMList:
def __init__(self):
user = 'contoso\\administrator'
password = "apassword"
url = "http://scspf:8090/SC2012/VMM/Microsoft.Management.Odata.svc/VirtualMachines?$filter=VMMServer%20eq%20'scvmm'"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
# create and install the opener
opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)
# retrieve the result
self.response = urllib2.urlopen(url)
self.data = self.response.read()
def name(self):
dom = parseString(self.data)
raw_xml = dom.getElementsByTagName('d:Name')
clean_xml = []
clean_data = []
for i in raw_xml:
clean_xml.append(i.toxml())
for i in clean_xml:
clean_data.append(i.replace('<d:Name>', '').replace('</d:Name>', ''))
return clean_data
def os(self):
dom = parseString(self.data)
raw_xml = dom.getElementsByTagName('d:OperatingSystem')
clean_xml = []
clean_data = []
for i in raw_xml:
clean_xml.append(i.toxml())
for i in clean_xml:
clean_data.append(i.replace('<d:OperatingSystem>', '').replace('</d:OperatingSystem>', ''))
return clean_data
实例化:
class ListHandler(tornado.web.RequestHandler):
def get(self):
self.render('temp/search.html', data='')
def post(self):
vm_list = GetVMList()
self.render('temp/search.html', data=vm_list)
然后模板包含以下内容:
{% for vm in data %}
<li>{{ vm.name }} running {{ vm.os }}</li>
{% end %}
错误是:TypeError: iteration over non-sequence
。我想我需要__iter__
在我的课堂上使用,但我不确定我是否完全理解它是如何工作的。