title: How to organize database connections in larger Python/Flask applications?
body: <p>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. </p>
  
  <p>Basically I've been following the "official" Tutorial (and <a href="http://flask.pocoo.org/docs/patterns/sqlite3/#sqlite3" rel="nofollow">http://flask.pocoo.org/docs/patterns/sqlite3/#sqlite3</a> ), leaving me with code like this in my main Flask/App module (drastically shortened):</p>
  
  <pre><code>@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")
  </code></pre>
  
  <p>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.<br>
  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:</p>
  
  <pre><code>from my_database_module import user_auth #
  
  @app.route("/login")
  def foo():
      if user_auth(request.form["name"], request.form["pw"]):
          pass
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>@app.route("/login")
  def foo():
      if user_auth(g.db, request.form["name"], request.form["pw"]):
          pass
  </code></pre>
  
  <p>and in my database-module</p>
  
  <pre><code>def user_auth(database, name, pw):
      pass
  </code></pre>
  
  <p>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.<br>
  tl;dr How to split Flask-App and Database/Database-Utility the right way?  </p>