Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use reflection/autoload in flask-sqlalchemy

I'm trying out flask-sqlalchemy in a simple test app. I'm running a SQL server, and I can connect to from Flask Using SQLalchemy like so:

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. 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.

Besides wondering how to do this; I'm also wondering:

  • Would the database reflection happen on every request or only at the start of the application? (This is a big database, so on every request would be a show-stopper)
  • is it possible to generate the code for the classes from the database and save them for later use, something like Django's inspectDB() does?

Thanks,

like image 669
Erik Oosterwaal Avatar asked Nov 16 '12 12:11

Erik Oosterwaal


1 Answers

Yes it is all possible. I use sqlautocode to do exactly what you are talking about. It generates sqlalchemy code to create the tables/column in sqlalchemy and places them in a file. 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:

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

Hope this helps

like image 111
nop snop Avatar answered Nov 14 '22 22:11

nop snop