for循环不迭代第二个值

2024-06-16 19:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

关于这个问题的一些解释代码:-取来自CmdForm(django form)的用户多个输入(逗号分隔)-->;在ipInsert中获取它--->;将它拆分并存储在ipIns中--->;然后迭代

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

在视图.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>

Tags: reformappoutputreturnrequesthtmlforms
1条回答
网友
1楼 · 发布于 2024-06-16 19:20:16

你的第一个for循环是

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

在第一次迭代之后,代码返回并停止执行。这就是为什么它在读了第一个条目之后就停止了。你知道吗

Edit:您要做的是让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+')

相关问题 更多 >