0

失败的 SQL:插入到 \"brand\" (\"brand_id\"、\"name\"、\"notification_email\"、\"notification_phone\"、\"created_at\"、\"updated_at\")值 (% (0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo 错误:{\'index\': 0, \' code\': 11000, \'errmsg\': \'E11000 重复密钥错误集合:f2fretaildev.brand index: name_1 dup key: { : \"shyamalas\" }\'}\nVersion: 1.2.26"

这是使用 djongo (django mongodb orm) 添加数据时重复键的错误

有没有办法将其中的 pymongo 错误作为 json 获取?我尝试了 json.dumps 和 json.loads 但这不起作用

4

1 回答 1

1

问题是错误消息的 JSON 格式不正确。我必须做一些调理;下面的代码只是给你一个方法。它非常脆弱,因为如果错误消息发生变化,它可能会失败 - 您将不得不处理边缘情况。

import json


error_msg = """
    FAILED SQL: INSERT INTO \"brand\" (\"brand_id\", \"name\", \"notification_email\", \"notification_phone\", \"created_at\",
     \"updated_at\") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo error: {\'index\': 0, \'code\': 11000, 
     \'errmsg\': \'E11000 duplicate key error collection: f2fretaildev.brand index: name_1 dup key: 
     { : \"shyamalas\" }\'}\nVersion: 1.2.26"
"""

key = "Unknown"
try:
    mongo_msg = error_msg.split('Pymongo error:')[1].split('Version:')[0].replace('\n','').replace('"','##')\
        .replace("'", '"').replace("{ :", " ").replace("## }", "##").replace('##', '')
    as_dict = json.loads(mongo_msg)
    error_msg = as_dict['errmsg']
    value = error_msg.split('key:')[1].strip()
    print(error_msg)
    print(value)
except:
    # Log it, print it, try something different
    pass
于 2018-05-14T15:30:51.940 回答