Question

I have a Flask application with which I'd like to use SQLAlchemy Core (i.e. I explicitly do not want to use an ORM), similarly to this "fourth way" described in the Flask doc:

http://flask.pocoo.org/docs/patterns/sqlalchemy/#sql-abstraction-layer

I'd like to know what would be the recommended pattern in terms of:

  1. How to connect to my database (can I simply store a connection instance in the g.db variable, in before_request?)

  2. How to perform reflection to retrieve the structure of my existing database (if possible, I'd like to avoid having to explicitly create any "model/table classes")

Was it helpful?

Solution

  1. Correct: You would create a connection once per thread and access it using a threadlocal variable. As usual, SQLAlchemy has thought of this use-case and provided you with a pattern: Using the Threadlocal Execution Strategy

    db = create_engine('mysql://localhost/test', strategy='threadlocal')
    db.execute('SELECT * FROM some_table')
    

    Note: If I am not mistaken, the example seems to mix up the names db and engine (which should be db as well, I think).

    I think you can safely disregard the Note posted in the documentation as this is explicitly what you want. As long as each transaction scope is linked to a thread (as is with the usual flask setup), you are safe to use this. Just don't start messing with threadless stuff (but flask chokes on that anyway).

  2. Reflection is pretty easy as described in Reflecting Database Objects. Since you don't want to create all the tables manually, SQLAlchemy offers a nice way, too: Reflecting All Tables at Once

    meta = MetaData()
    meta.reflect(bind=someengine)
    users_table = meta.tables['users']
    addresses_table = meta.tables['addresses']
    

    I suggest you check that complete chapter concerning reflection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top