简体   繁体   English

如何从 flask-SQLAlchemy 查询一个 SQL View

[英]How to query a SQL View from flask-SQLAlchemy

I have been given access to a database (MySQL, in case it matters) to access some data that I need, but I don't have direct access to the tables, the data is exposed through a SQL View.我有权访问数据库(MySQL,以防万一)以访问我需要的一些数据,但我无法直接访问表,数据通过 SQL 视图公开。

I want to wrap this in a small API using flask. For the database connection I intend to use SQLAlchemy (just because it's the only databse wrapper that I know in python).我想使用 flask 将它包装在一个小的 API 中。对于数据库连接,我打算使用 SQLAlchemy(只是因为它是我在 python 中知道的唯一数据库包装器)。

The thing is, I have read a lot of documentation, and dozens of stackoverflow posts and guides through the Inte.net, and I can't seem to find a way to query SQL Views from flask-SQLAlchemy.问题是,我已经通过 Inte.net 阅读了很多文档、数十篇 stackoverflow 帖子和指南,但我似乎无法找到一种方法来查询来自 flask-SQLAlchemy 的 SQL Views。

In the documentation, they always use Models.在文档中,他们总是使用模型。 I tried to define my View as a Model, but I get could not assemble any primary key columns for mapped table 'MySQLView' .我试图将我的视图定义为 Model,但我得到could not assemble any primary key columns for mapped table 'MySQLView'

What I tried to do:我试图做什么:

class MyView(db.Model):
    __tablename__ = "my_view_name_in_sql"
    db.Column("id", db.Integer, primary_key=True)
    db.Column("sample_id", db.String)
    {...etc}

Is there a way to do this, or maybe I should opt-out of using flask-SQLAlchemy and use something else instead?有没有办法做到这一点,或者我应该选择不使用 flask-SQLAlchemy 并改用其他东西?

There's a few answers here I think deal with your case, especially LeoRochael's answer who suggests using the https://pypi.org/project/sqlalchemy-views/ package. I suggest checking if you can - or cannot access the database's metdata, I think that could really help you avoid having to make models manually我认为这里有一些答案可以处理您的情况,尤其是 LeoRochael 的答案,他建议使用https://pypi.org/project/sqlalchemy-views/package 。我建议检查您是否可以 - 或不能访问数据库的元数据,我认为这真的可以帮助您避免手动制作模型

db_engine = sqlalchemy_package.create_engine("mysql+...")
db_metadata = db.MetaData(bind=db_engine)

you can then either try making a Table directly, or use the metadata to make views like in the answer I linked.然后您可以尝试直接制作表格,或者使用元数据制作视图,就像我链接的答案一样。

your_table = db.Table("my_view_name_in_sql", db_metadata, autoload=True)
view_definition = your_table.select()
your_view = CreateView(your_table, view_definition, or_replace=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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