SQLAlchemy automap - adding methods to automapped Model
<p>I have a preexisting database that I'm using with SQLAlchemy, so I'm using automap to get the Models from the database. What is the best way to add methods to these classes? For example, for a User class, I'd like to add methods such as verifying the password. Also, I'd like to add methods for flask-login (UserMixin) methods.</p>

<p><a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html#specifying-classes-explicitly" rel="nofollow">Specify your classes explicitly</a> beforehand, and define your methods as you would normally:</p>

<pre><code>Base = automap_base()

class User(Base):
    __tablename__ = 'user'

    def verify_password(self, password):
        ...

Base.prepare(engine, reflect=True)
</code></pre>

<p>Now <code>Base.classes.User</code> and <code>User</code> are the same, with your additional methods. To make your <code>User</code> class flask-login compatible, implement the <a href="https://flask-login.readthedocs.io/en/latest/#your-user-class" rel="nofollow">listed attributes and methods</a>, or add the provided <a href="https://github.com/maxcountryman/flask-login/blob/master/flask_login/mixins.py#L12" rel="nofollow"><code>UserMixin</code></a> to your <code>User</code> class. The mixin seems to only expect the existence of an <code>id</code> attribute/column from your <code>User</code> class.</p>

python flask sqlalchemy flask-sqlalchemy