[英]How do I use reflection/autoload in flask-sqlalchemy
I'm trying out flask-sqlalchemy in a simple test app. 我在一个简单的测试应用程序中尝试使用flask-sqlalchemy。 I'm running a SQL server, and I can connect to from Flask Using SQLalchemy like so:
我正在运行SQL服务器,我可以从Flask使用SQLalchemy连接到这样:
from flask import render_template
from app import app, db
@app.route('/')
@app.route('/index')
def index():
people = list(db.session.execute("select top 10 * from people where ppl_username IS NOT NULL"))
However, I would also like to use the SQL psuedo language and ORM part of SQLalchemy to query. 但是,我还想使用SQL伪造语言和SQLalchemy的ORM部分进行查询。 Because this is an existing database I don't want to write my own classes and generate a database, I would like to reflect the existing database and access it that way.
因为这是一个现有的数据库,我不想编写自己的类并生成数据库,我想反映现有的数据库并以这种方式访问它。 I have found the reflect method in the API docs , but I can't figure out how (and where) to use that.
我在API文档中找到了reflect方法 ,但我无法弄清楚如何(以及在何处)使用它。
Besides wondering how to do this; 除了想知道如何做到这一点; I'm also wondering:
我也想知道:
Thanks, 谢谢,
Yes it is all possible. 是的,这一切都是可能的。 I use sqlautocode to do exactly what you are talking about.
我使用sqlautocode完全按照你所说的去做。 It generates sqlalchemy code to create the tables/column in sqlalchemy and places them in a file.
它生成sqlalchemy代码以在sqlalchemy中创建表/列并将它们放在一个文件中。 Simply install it and then from the command line run it.
只需安装它,然后从命令行运行它。
This generates the models sqlalchemy models from an existing mysql db for my webapp and creates a file alchemy_models.py: 这将从我的webapp的现有mysql数据库生成模型sqlalchemy模型,并创建一个文件alchemy_models.py:
sqlautocode mysql://<dbuser>:<pass>@localhost:3306/<dbname> -o alchemy_models.py
Note the mysql:// bit is merely the syntaxt to generate a connection in SA 注意mysql:// bit只是在SA中生成连接的语法
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.