如何在`flask-admin`中执行约束? [英] How to enforce constraints in `flask-admin`?

查看:178
本文介绍了如何在`flask-admin`中执行约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 http://flask-admin.readthedocs.org/ 管理界面。
我们的模型有如下定义的约束:

$ $ $ $ $ c $ __ table_args__ =(
db.UniqueConstraint(user_id,role ,domain_id),
db.UniqueConstraint(user_id,role,customer_id),



当在调试模式下保存违反约束条件的记录时,应用程序停止追溯。如果不处于调试模式,则会在闪存消息中报告错误并回退事务。

这是所需的行为(即flash消息和回滚)。用户做了错误的事情,并防止输入错误的数据:这不是一个错误,应该显示回溯。



优雅地处理这种异常的正确的Flask方法是什么?我应该重写 {create,update,delete} _model 方法 ModelView

$ b $你可以实现on_model_change和on_model_delete函数。因此,您可以检查数据是否是唯一的,并在不满足约束的情况下提供更友好的消息。下面是在删除/插入/更新操作之前检查一些约束的一个例子:
$ b $ pre $ class ExampleView(ModelView):
def on_model_delete(self,model):
#check约束

$ b $ def on_model_change(self,form,model,is_created):
#insert
if被创建:
#check约束
#update
else:
#check约束


We're using http://flask-admin.readthedocs.org/ for a quick admin interface. Our model has constraints defined as follows:

__table_args__ = (
        db.UniqueConstraint(user_id, role, domain_id),
        db.UniqueConstraint(user_id, role, customer_id),
        )

When saving a record that violates a constraint while in debug mode, the app stops with a traceback. If not in debug mode, it reports the error in a flash message and rolls back the transaction.

This is the desired behaviour (i.e. flash message and rollback). The user did something wrong and was protected from entering bad data: it's not an error that should show a traceback.

What is the proper Flask way of handling such exceptions elegantly? Should I be overriding the {create,update,delete}_model methods of ModelView?

解决方案

You can implement the on_model_change and on_model_delete functions. So you can check if the data is unique and give a more user friendly message in case a constraint is not satisfied. Here is an example of checking some constraints before the delete/insert/update operation

class ExampleView(ModelView):
    def on_model_delete(self, model):
        #check constraint


    def on_model_change(self, form, model, is_created):
        #insert 
        if is created:
            #check constraint
        #update
        else:
            #check constraint

这篇关于如何在`flask-admin`中执行约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆