异常处理中的python / Django语法错误

时间:2019-07-15 06:07:48

标签: python django

在下面的代码中,我在错误处理语句中收到syatax错误' 我正在使用ATOM文本编辑器。 django用于网络界面,netmiko libaray用于我的后端代码。

from django.shortcuts import render
from first_app.forms import CmdForm
from django.http import HttpResponse
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException
import datetime, time, sys
   # Create your views here.

def index(request):
    my_dict = {'insert_me': ""}
    return render(request,'first_app/index.html',context=my_dict)

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', '')
            devices = {
            'device_type':'cisco_ios',
            'ip':ipInsert,
            'username':'mee',
            'password':'12345',
            'secret':'12345',
            }
            cmd = request.POST.get('command', '')
            try:
                netconnect = ConnectHandler(**devices)
            except(AuthenticationException):
                print ('Authentication failed' + ipInsert)
            continue           #position 1
                continue       #posiiton 2
            getIP = netconnect.send_command(ipInsert)
            output = netconnect.send_command(cmd)
            now = time.strftime("%Y_%m_%d__%H_%M%S")
            file = sys.stdout
            file = open("C:/Users/karti/OneDrive/Desktop/frontend/ "+now +".txt", mode='w+')
            file.write("IP address is\n"+ ipInsert)
            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})
        else:
            form = CmdForm()
        return render(request,'first_app/forms.html', {'form': form})
    else:
        return render(request,'first_app/forms.html', {})

在位置1继续时出错

  

从first_app导入视图     文件“ K:\ Work \ DevNet \ first_project \ first_app \ views.py”,第33行       继续       ^   SyntaxError:“继续”未正确循环

在位置2继续时出错

  

文件“ K:\ Work \ DevNet \ first_project \ first_app \ views.py”,第33行       继续       ^   SyntaxError:“继续”未正确循环

2 个答案:

答案 0 :(得分:0)

  • 在python中,由于不正确的对齐方式,程序中可能存在错误,tryException似乎没有对齐。
  • 每次尝试都应该有一个except块,您可以在其中捕获try块引发的异常。
  • 此外,第31行似乎有错误,但发布的代码较少

答案 1 :(得分:0)


以下代码是正确的:

cmd = request.POST.get('command', '')
try:
    netconnect = ConnectHandler(**devices)
except Exception as e:
    print ('Authentication failed' + ipInsert)
    continue
getIP = netconnect.send_command(ipInsert)