在无调试模式下无法在create_view()中捕获异常

时间:2019-07-26 15:38:37

标签: python mongoengine flask-admin

我在create_view()中重写了mongoengine.ModelView方法:

from mongoengine.errors import NotUniqueError
from pymongo.errors import DuplicateKeyError


class MyView(mongoengine.ModelView):
@expose('/create/', methods=('GET', 'POST'))
    def create_view(self):
        try:
            return super(MyView, self).create_view()
        except (NotUniqueError, DuplicateKeyError):
            flash('Duplicated search word! Redirected to existing record.', 'error')

            # redirect logic here
            location = "/"
            return redirect(location)

使用NotUniqueError运行服务器时,我能够捕获到app.run(debug=True)异常。

但是如果debug=False的{​​{1}}块被忽略:

try:except

1 个答案:

答案 0 :(得分:0)

方法create_view中不会发生异常,而方法create_model中不会发生异常。它在堆栈跟踪中告诉您:

Traceback (most recent call last):
  File "/home/pata/venvs/lib/python3.6/site-packages/flask_admin/contrib/mongoengine/view.py", line 566, in create_model
    model.save()

还要注意Flask-Admin在调试和生产环境中处理mongoengine exceptions的不同方式。

您需要做的是覆盖create_model并在那里处理您的特定异常情况,例如

class MyView(mongoengine.ModelView):

    def create_model(self, form):
        """
            Create model helper
            :param form:
                Form instance
        """
        try:
            model = self.model()
            form.populate_obj(model)
            self._on_model_change(form, model, True)
            model.save()
        except (NotUniqueError, DuplicateKeyError):

            # Your code here

        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s',
                              error=format_error(ex)),
                      'error')
                log.exception('Failed to create record.')

            return False
        else:
            self.after_model_change(form, model, True)

        return model