如何在`flask-admin`中执行约束? [英] How to enforce constraints in `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 $ 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屋!