如何向python函数添加异常?

问题描述 投票:0回答:2

美好的一天。我在python上编写了一个应用程序,该应用程序从Avaya PBX收集呼叫日志,并将其写入mysql数据库。它工作正常,但有时PBX由于某种原因发送空字符串,并且程序失败。我在下面附上屏幕和代码。我们了解到您需要将函数包装在一个异常中:尝试除,但我不知道该怎么做。请告诉我该怎么做。enter image description here


def write_db(item, *agrs):
    connection = pymysql.connect(host='localhost',
                                 user='acdr',
                                 password='it8ejokd',
                                 db='avaya_cdr',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    DBTBL = "cdr102019"
    DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"

    dep_num_call = find_dep(item[3].replace(' ', ''))
    name_dep_call = name_dep(dep_num_call)
    dep_num_dial = find_dep(item[4].replace(' ', ''))
    name_dep_dial = name_dep(dep_num_dial)

    item.append(name_dep_call)
    item.append(name_dep_dial)
    item[1] = item[1] + "00"

    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
            cursor.execute(sql, (item))
        connection.commit()
    finally:
        connection.close()

# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)

# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')

# Слушаем запросы и пишем в db
while True:
    connection, address = server_socket.accept()

    data = connection.recv(1024)
    if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
        str = data.decode("utf-8")
        item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
        print(item)
        write_db(item)

    connection.close()
python mysql-python mysql-error-1064
2个回答
0
投票

您必须捕获异常,因此我们可以满足几种类型,但是为确保并使您开始运行,您可以执行以下操作:)

try:
    with connection.cursor() as cursor:
        sql = (
                "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES " 
                "(%s,%s,%s,%s,%s,%s,%s)"
        )
        cursor.execute(
            sql,
            (item),
        )

    connection.commit()

except Exception as e:
    print("Error occurred: %s"% e)

finally:
    connection.close()

-1
投票

这应该可以解决问题。我在这里使用了try / except / else / finally的所有四个元素,并简要说明了它们何时执行。

try:
    with connection.cursor() as cursor:
        sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
        cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
    pass
else: # If the code inside 'try' succeeds, execute this code. 
    connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
    connection.close()
© www.soinside.com 2019 - 2024. All rights reserved.