title: Connect to a Database in Flask, Which Approach is better?
body: <p>Method One: Using special g object from <a href="http://flask.pocoo.org/docs/tutorial/dbcon/" rel="noreferrer">http://flask.pocoo.org/docs/tutorial/dbcon/</a> and <a href="http://flask.pocoo.org/docs/patterns/sqlite3/" rel="noreferrer">http://flask.pocoo.org/docs/patterns/sqlite3/</a></p>
  
  <pre><code>import sqlite3
  from flask import g
  
  DATABASE = '/path/to/database.db'
  
  def connect_db():
      return sqlite3.connect(DATABASE)
  
  @app.before_request
  def before_request():
      g.db = connect_db()
  
  @app.teardown_request
  def teardown_request(exception):
      if hasattr(g, 'db'):
          g.db.close()
  </code></pre>
  
  <p>Method Two: Using Mysterious _app_ctx_stack from <a href="https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py" rel="noreferrer">https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py</a></p>
  
  <pre><code>from sqlite3 import dbapi2 as sqlite3
  from flask import Flask, request, session, g, redirect, url_for, abort, \
       render_template, flash, _app_ctx_stack
  def get_db():
      """Opens a new database connection if there is none yet for the
      current application context.
      """
      top = _app_ctx_stack.top
      if not hasattr(top, 'sqlite_db'):
          top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
      return top.sqlite_db
  
  
  @app.teardown_appcontext
  def close_db_connection(exception):
      """Closes the database again at the end of the request."""
      top = _app_ctx_stack.top
      if hasattr(top, 'sqlite_db'):
          top.sqlite_db.close()
  </code></pre>
  
  <p>Which method is better? What is the difference?</p>