title: how to use after_request in flask to close database connection and python?
body: <p>How to use after_request decorator to close a connection after the request is processed? I use the before_request for opening the connection for each api request as follows:
  Using sqlalchemy core 1.0.8 and postgresql 9.5:</p>
  
  <pre><code>#engine = create_engine(os.environ.get("DB_URL"))
  DB_URL="postgresql://mowner:passwd@localhost/mydb"
  
  @app.before_request
  def before_request():
      engine = create_engine(DB_URL, strategy='threadlocal')
      conn = engine.connect()
  
  
  @app.after_request
  def after_request(conn):
       if conn is not None:
           print 'closing connection'
           conn.close()
  </code></pre>
  
  <p>sample api call:</p>
  
  <pre><code>@app.route('/api/v1.0/categories', methods=['GET'])
  def categories_list():
      '''
      Return categories list
      '''
      if 'id' in session:
          categories_list = []
          s = select([categories])
          rs = conn.execute(s)
          if rs.rowcount &gt; 0:
              for r in rs:
                  categories_list.append(dict(r))
              rs.close()
          # print 'this doesnt execute'
          return jsonify({'categories list': categories_list}), 200
  
      return jsonify({'message': "UNAUTHORIZED"}), 401
  </code></pre>
  
  <p>The views are api calls which only return a list of objects, added, or edit object and a message. How exactly to pass the connection object to the after_request decorator? I couldn't really follow the documentation 
  Exact code will help me.</p>