python 3.6 mongoengine无法捕获异常

时间:2016-06-20 06:10:59

标签: python django python-3.x mongoengine pymongo-3.x

我有一个django 1.9项目,并使用mongoengine连接到mongodb实例。

我的模型如下:

from django.db import models
from mongoengine import * 
class Employee(Document):
    email = StringField(required=True, unique=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

测试类:

import web.models as models
class test:

    '''Test the accessibility of the business class'''
    def testBusiness():
        employee = models.Employee.objects.create(
            email="pedro.kong@company.com",
            first_name="Pedro",
            last_name="Kong"
        )
        try:
            employee.save()
        except pymongo.errors.DuplicateKeyError as e:
            return "Error"
        return "Business Tested"

问题在于我无法捕捉DuplicateKeyError执行:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: rockynode.employee.$email_1  dup key: { : "pedro.kong@company.com" }

我尝试使用全局尝试,但它仍然以DuplicateKeyError异常崩溃代码:

try:
    employee.save()
except:
    return "Error"
return "Business Tested"

对于使用以下依赖项的信息:​​

  

Django == 1.9.7
  mongoengine == 0.10.6
  pymongo == 3.2.2

R效率:get-the-duplicate-value-on-duplicatekeyerror

任何帮助都会非常值得赞赏.Thx。

2 个答案:

答案 0 :(得分:1)

我必须解决这个问题。

try except无效,因为DuplicateKeyError exception方法未触发save(),而是create()方法。

引证文件:create()

  

创建新对象。返回保存的对象实例。

mongoengine代码def create()中的代码部分:Reff:Monogoengine code清楚地显示create()函数调用save()函数:

从mongoengine代码中提取:

def create(self, **kwargs):
        """Create new object. Returns the saved object instance.
        .. versionadded:: 0.4
        """
        return self._document(**kwargs).save()

因此,我的try块必须包含create()方法,如下所示:

 try:
            employee = models.Employee.objects.create(
                email="pedro.kong@company.com",
                first_name="Pedro",
                last_name="Kong"
            )
            employee.save()
        except Exception as e:
            return "Error \n %s" % (e)
        return "Business Tested"

答案 1 :(得分:1)

正如您在文档中看到的那样,create会返回已保存的文档,因此如果您使用它,

  • 你不必再次保存
  • 你必须在那里捕获保存例外

    try:
        employee = models.Employee.objects.create(
            email="pedro.kong@company.com",
            first_name="Pedro",
            last_name="Kong"
        )
    except Exception as e:
        return "Error \n %s" % (e)
    return "Business Tested"
    

或者如果您不使用创建但保存在单独的声明中:

    employee = models.Employee(
        email="pedro.kong@company.com",
        first_name="Pedro",
        last_name="Kong"
    )
    try:
        employee.save()
    except Exception as e:
        return "Error \n %s" % (e)
    return "Business Tested"