Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

python - Query property for models in sqlalchemy 1.4-2.0

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.

E.g. we can do smth 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 appeares, 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 quering style to asyncronious 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?

question from:https://stackoverflow.com/questions/65890188/query-property-for-models-in-sqlalchemy-1-4-2-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...