我的视图功能在终端中打印所有列表,但在模板(web,html页面)中仅显示1行,如何为类似终端输出的代码修复我的代码
/views.py
def snmpWALK(request):
if request.method=='GET':
host= 'localhost'
oid = '1.3.6.1.2.1.1.9.1.2'
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in nextCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((host, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid)),
lookupMib=False,
lexicographicMode=False):
if errorIndication:
print(errorIndication, file=sys.stderr)
break
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr)
break
else:
MyList = []
for varBind in varBinds:
thing='%s = %s' % varBind
MyList.append(thing)
print (MyList)
return render(request, 'snmpWALK.html', {'MyList':MyList})
/snmpWALK.html
{% block content %}
{{MyList}}
{% endblock %}
终端打印
['1.3.6.1.2.1.1.9.1.2.1 = 1.3.6.1.6.3.11.3.1.1']
['1.3.6.1.2.1.1.9.1.2.2 = 1.3.6.1.6.3.15.2.1.1']
['1.3.6.1.2.1.1.9.1.2.3 = 1.3.6.1.6.3.10.3.1.1']
['1.3.6.1.2.1.1.9.1.2.4 = 1.3.6.1.6.3.1']
['1.3.6.1.2.1.1.9.1.2.5 = 1.3.6.1.6.3.16.2.2.1']
['1.3.6.1.2.1.1.9.1.2.6 = 1.3.6.1.2.1.49']
['1.3.6.1.2.1.1.9.1.2.7 = 1.3.6.1.2.1.4']
['1.3.6.1.2.1.1.9.1.2.8 = 1.3.6.1.2.1.50']
['1.3.6.1.2.1.1.9.1.2.9 = 1.3.6.1.6.3.13.3.1.3']
['1.3.6.1.2.1.1.9.1.2.10 = 1.3.6.1.2.1.92']
网页打印
['1.3.6.1.2.1.1.9.1.2.10 = 1.3.6.1.2.1.92']
答案 0 :(得分:0)
缩进肯定会使您的代码很难阅读。我怀疑您看到多个列表的原因是您的print
调用位于for
循环内。解决方法如下:
def snmpWALK(request):
all_lists = []
if request.method=='GET':
host= 'localhost'
oid = '1.3.6.1.2.1.1.9.1.2'
for t in nextCmd(
SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((host, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid)),
lookupMib=False,
lexicographicMode=False):
# I broke this up for purposes of formatting
# on SO. normally, I would just stick these in
# the for loop above.
errorIndication, errorStatus = t[0], t[1]
errorIndex, varBinds = t[2], t[3]
if errorIndication:
print(errorIndication, file=sys.stderr)
break
elif errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
), file=sys.stderr)
break
else:
MyList = []
for varBind in varBinds:
thing='%s = %s' % varBind
MyList.append(thing)
# this is within the for loop!!!
print(MyList)
all_lists.append(MyList)
return render(request, 'snmpWALK.html', {'MyList': all_lists})
通常来说,对于喜欢SO的我们来说,您的代码很难阅读,因为(1)缩进不正确(您可以在OP中看到break
语句)和(2 ),它没有遵循PEP8。 YMMV如果您想遵循这些约定/建议,则可以轻松地为您提供帮助。