title: Psycopg2 & Flask - tying connection to before_request & teardown_appcontext
body: <p>Cheers guys,
  refactoring my Flask app I got stuck at tying the db connection to <code>@app.before_request</code> and closing it at <code>@app.teardown_appcontext</code>. I am using plain Psycopg2 and the app factory pattern.</p>
  
  <p>First I created a function to call wihtin the app factory so I could use @app as <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure" rel="nofollow noreferrer">suggested by Miguel Grinberg here</a>:</p>
  
  <pre><code>def create_app(test_config=None):
      app = Flask(__name__, instance_relative_config=True)
  
      --
  
      from shop.db import connect_and_close_db
      connect_and_close_db(app)
  
      --
  
      return app
  </code></pre>
  
  <p>Then I tried this pattern suggested on <a href="http://flask.pocoo.org/docs/1.0/appcontext/#storing-data" rel="nofollow noreferrer">http://flask.pocoo.org/docs/1.0/appcontext/#storing-data</a>:</p>
  
  <pre><code>def connect_and_close_db(app):
  
      @app.before_request
      def get_db_test():
          conn_string = "dbname=testdb user=testuser password=test host=localhost"
          if 'db' not in g:
              g.db = psycopg2.connect(conn_string)
          return g.db
  
      @app.teardown_appcontext
      def close_connection(exception):
          db = g.pop('db', None)
  
          if db is not None:
              db.close()
  </code></pre>
  
  <p>It resulted in:</p>
  
  <pre><code>TypeError: 'psycopg2.extensions.connection' object is not callable
  </code></pre>
  
  <p>Anyone has an idea what happend and how to make it work?</p>
  
  <p>Furthermore I wonder how I would access the connection object for creating a cursor once its creation is tied to <code>before_request</code>?</p>