首页 > 解决方案 > for 循环不迭代第二个值

问题描述

关于代码的一些解释:-从CmdForm(django表单)中获取用户的多个输入(逗号分隔)--->在ipInsert中获取它---->将其拆分并存储在ipIns中--->然后迭代

但问题是当我采用逗号分隔值时,for 循环不会第二次迭代。在逗号前显示输入结果。

在views.py

def form_name_view(request):
    if request.method == "POST":
        form = CmdForm(request.POST)
        if form.is_valid():
            from netmiko import ConnectHandler
            ipInsert = request.POST.get('ip_address', '')
            ipIns = ipInsert.split(',')
            for ipIn in ipIns:
                devices = {
                'device_type':'cisco_ios',
                'ip':ipIn,
                'username':'mee',
                'password':'12345',
                'secret':'12345',
                }
                cmd = request.POST.get('command', '')
                try:
                    netconnect = ConnectHandler(**devices)
                except (AuthenticationException):
                    re = 'Authentication failed.! please try again {}'.format(ipIn)
                    print(re)
                    return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                    pass
                except (SSHException):
                    re = 'SSH issue. Are you sure SSH is enabled? {}'.format(ipIn)
                    print(re)
                    return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                    pass
                except (NetMikoTimeoutException):
                    re = 'TimeOut to device {}'.format(ipIn)
                    print(re)
                    return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                    pass
                except (EOFError):
                    re = 'End of file while attempting device {}'.format(ipIn)
                    print(re)
                    return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                    pass
                except Exception as unknown_error:
                    re = 'Some other error {}' .format(unknown_error)
                    print(re)
                    return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                    pass

                getIP = netconnect.send_command(ipIn)
                output = netconnect.send_command(cmd)
                now = time.strftime("%Y_%m_%d__%H_%M_%S")
                file = sys.stdout
                file = open("C:/Users/OneDrive/Desktop/frontend/ "+now +".txt", mode='w+')
                file.write("IP address is\n"+ ipIn)
                file.write("\n\nCommand Executed: \n"+ cmd)
                file.write("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                file.write("\n\nOutput of Executed Command: \n\n\n"+output)
                file.close
                return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})


            #return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})

            #return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})
        else:
            form = CmdForm()
            return render(request,'first_app/forms.html', {'form': form})
    else:
        return render(request,'first_app/forms.html', {})

这是 HTML 代码:-

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>FORMS</title>
    </head>
  <body>
    <h1> To run Commands </h1>

<br><br>
<form method="POST"> {% csrf_token %}
{{ form }}
<br><br>
<input type="submit" value="Click Here to run Commands" />
<br>

{% if request.POST %}
<pre>{{ reprinting }}</pre>
{% endif %}

<br>
{% if request.POST %}
{% csrf_token %}
<p>Current date and time is : {{ date_time }} </p>
<p>Command output:</p>
<pre>{{ output }}</pre>
{% endif %}


</form>
  </body>
</html>

标签: pythonhtmldjango

解决方案


你的第一个 for 循环是

for ipIn in ipIns:
            [...]
            return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})

第一次迭代后,代码返回并停止执行。这就是为什么它在阅读第一项后停止的原因。

编辑:你想要做的是让你的 for 循环并在它之后有 return 语句(确保你得到正确的缩进):

for ipIn in ipIns:
    [...]
return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})

编辑2:另外,您正在覆盖而不是附加。改变

file = open("C:/Users/karti/OneDrive/Desktop/frontend/ "+now +".txt", mode='w+')

file = open("C:/Users/karti/OneDrive/Desktop/frontend/ "+now +".txt", mode='a+')

推荐阅读