如何从 Flask-appbuilder 和 SQLAInterface 中的操作更新数据库行

How to update a db row from an action in Flask-appbuilder and SQLAInterface

我正在使用 flask-appbuilder 构建一个应用程序,我有一个运行函数的操作,我想用函数的输出更新 table 中的行。不知道该怎么做。有什么帮助吗?谢谢

@action("prospect", "Prospect", "off we go", "fa-rocket")
def prospect(self, items):
    if isinstance(items, list):
        for a in items:
            out = self.myfunction(a.name)
            #Need to update the table with output
            #anyideas?
        self.update_redirect()
    else:
        print "nothing"
    return redirect(self.get_redirect())

我假设这是一个与模型相关的视图。如果是这种情况,您可以使用 Flask-AppBuilder SQLAInterface class 将模型与视图相关联。 class 允许您与数据库中的项目进行交互。

这个 class 有一个 'edit' 方法让你更新项目。

假设您的模型如下所示:

class Contact(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique = True, nullable=False)

假设您要执行将联系人姓名大写的操作,并且您希望能够在 'List' 和 'Show' 视图上执行此操作。这是一种方法:

class ContactView(ModelView):
    datamodel = SQLAInterface(Contact)

    @action("capitalize",
            "Capitalize name",
            "Do you really want to capitalize the name?")
    def capitalize(self, contacts):
        if isinstance(contacts, list):
            for contact in contacts:
                contact.name = contact.name.capitalize()
                self.datamodel.edit(contact)
                self.update_redirect()
        else:
            contacts.name = contacts.name.capitalize()
            self.datamodel.edit(contacts)
        return redirect(self.get_redirect())

您可以检查其他 SQLAInterface 方法here