简体   繁体   中英

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

I am building a app using flask-appbuilder and I have an action that runs a function and I want to update the row in the table with the output of function. Can't work out how to do it. Any help? Thanks

@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())

I'm assuming this is a View that is related to a model. If this is the case, you relate the model to the view using Flask-AppBuilder SQLAInterface class. This class allows you to interact with the item in the database.

This class has an 'edit' method that let's you update the item.

Let's say your model is like the one below:

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

Let's say you want to implement an action that capiltalizes the contact name, and you want to be able to do it on the the 'List' and 'Show' views. This is one way to do it:

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())

You can check other SQLAInterface methods here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM