Query property for models in sqlalchemy 1.4-2.0

Viewed 279

When we are using Flask we know, that we can declare our models and either map them for INSERTS or map SELECT results into these models.

For example, we can do something like this:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample.db'

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    password = db.Column(db.String(80))
    admin = db.Column(db.Boolean) 
    def __init__(id, name, password, admin):
        self.id = id
        self.name = name
        self.password = password
        self.admin = admin

@app.route('/user', methods=['GET'])
def get_all_users(current_user):       
    users = User.query.all()
    ...

Here in users we do not query our data like it's written in the official docs:

session.query(User).all()

Just User.query.all() and it's perfect - we get all we need. It's so amazing, isn't it?!

For applying this option in any other (not-Flask) project we can do smth like that:

Base = declarative_base()

class Connect:
    engine = create_engine(conf.DATABASE_URI)
    DBSession = scoped_session(sessionmaker(bind=engine))
    session = DBSession()


class Query(Connect):
    query = Connect.DBSession.query_property()


class User(Base, Query):
     ...

That will bring us to the same behaviour of the our User-model. We are able to query just from the model and map the results into it. Updates, deletes, Model.query.get(<your_primary_key>) - anything is available.

To my mind it's so great that I can't imagine my coding without it. But when we are facing ASYNC versions of ORMs, engines and so on it appears that either we have to make raw sql-queries or use long-length code.

I've read docs for SQLAlchemy 1.4-2.0 and failed to find any possibility of applying above mentioned querying style to asynchronuous coding. Even if we are going to use

await AsyncSession(bind=async_engine).run_sync(function_quering_smth)

it seems impossible to implement it.

So, please, tell me: am I right and it is really impossible and nothing can be done OR am I wrong, and there is a way?

0 Answers
Related