How to organize database connections in larger Python/Flask applications?
Question: I am currently trying to write a little web-application using python, flask
and sqlite and I'm not sure about how to handle the database-connections.

Basically I've been following the "official" Tutorial (and
<http://flask.pocoo.org/docs/patterns/sqlite3/#sqlite3> ), leaving me with
code like this in my main Flask/App module (drastically shortened):

    
    
    @vs_app.before_request
    def before_request():
        g.db = sqlite3.connect("somedb.db")
    
    def execute_db(command):
        return g.db.cursor().execute(command).fetchall()
    
    @app.route("/givemeallusers")
    def foo():
        return execute_db("SELECT * FROM users")
    

So this creates a DB-Connection for each request that can be used by my
application to execute sql-commands and it works fine for smaller
applications.  
But for a larger project I'd like to put my database-code (with some utility
methods) and app-code in different modules, so I could (for example) write:

    
    
    from my_database_module import user_auth #
    
    @app.route("/login")
    def foo():
        if user_auth(request.form["name"], request.form["pw"]):
            pass
    

But for that I would need access to g (or g.db) from my database-class and the
only way I could get that to work was by "manually" handing over the db-
connection to each method, leaving me with code like this:

    
    
    @app.route("/login")
    def foo():
        if user_auth(g.db, request.form["name"], request.form["pw"]):
            pass
    

and in my database-module

    
    
    def user_auth(database, name, pw):
        pass
    

I don't think thats the best approach, but other ideas I had (like importing
the g object into my database-class) don't work. I also don't know whether my
approach is safe with regards to concurrent db-access, so any help with this
would be appreciated.  
tl;dr How to split Flask-App and Database/Database-Utility the right way?


Answer: Just in case someone stumbles upon this question:  
The correct answer is to not bother with the approaches described in the
Question, and instead just start working with Flask-SQLAlchemy.

