How to enforce constraints in `flask-admin`?

点点圈 提交于 2019-12-10 11:38:51

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30025641/how-to-enforce-constraints-in-flask-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!