Flask-SQLAlchemy– Can you make a query within a model?

六眼飞鱼酱① 提交于 2020-05-13 18:06:23

问题


I'm building a flask webapp which uses Flask-SQLAlchemy, and I'm also considering using Flask-Login to take care of sessions and to protect certain views.

Flask-Login requires certain methods which I see as useful for various parts of the app (specifically, is_authenticated() and is_active(). However, in all of the examples I've seen these methods just return something fixed. What if I want to make a query on the database. For example, if I want to check if that user actually has an entry in the table (I'm using LDAP to log in, so want users to be able to log in even if they haven't got an entry in the table, although I need to see if they are there).

But I don't know if it's possible to make a query on the table itself from within the class which defines it? Or should I place these functions elsewhere (even though the methods are needed by flask-login within the user class)?


回答1:


You can. Usually the Session.object_session is a good way to get a session and perform a query:

class MyModel(Base):
    __tablename__ = u'model_table'
    id = Column(Integer, primary_key=True)
    # ...

    def my_method(self):
       session = Session.object_session(self)
       qry = session.query(...).filter(...)
       # ...



回答2:


Flask-Login requires that you provide a user object in the user loader callback. This user does not need to be backed by a database entry, it can be any object as long as it implements the required methods such as is_authenticated() and is_active().

From your description it seems to me that the representation of a user that you need is not one that maps one to one to the user table in your database, since you have valid users that are not in your database.

One approach that you can take is to have two user classes, both implementing the required methods. Let's call these DBUser and LDAPUser. As long as you figure out a strategy to have unique IDs across instances of the two classes Flask-Login will not care.

The DBUser class can be a proper database model based on Flask-SQLAlchemy, with straightforward implementations of the is_xxx() methods. The LDAPUser class, on the other side, can implement these methods issuing any necessary database queries into DBUser.query.



来源:https://stackoverflow.com/questions/20595226/flask-sqlalchemy-can-you-make-a-query-within-a-model

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