title: Flask-SQLAlchemy fails to update data in while in thread
body: <p>I am building an app where users will occasionally initiate a longer-running process. While running, the process will commit updates to a database entry.</p>
  
  <p>Since the process takes some time, I am using the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow noreferrer">threading</a> module to execute it. But values updated while in the thread are never actually committed.</p>
  
  <p>An example:</p>
  
  <pre><code>from flask import Flask, url_for, redirect
  from flask_sqlalchemy import SQLAlchemy
  import time, threading, os
  
  if os.path.exists('test.db'): os.remove('test.db')
  
  app = Flask(__name__)
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  db = SQLAlchemy(app)
  
  class Item(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      value = db.Column(db.Integer)
      def __init__(self, value): self.value = value
  
  db.create_all()
  
  item = Item(1)
  db.session.add(item)
  db.session.commit()
  
  @app.route('/go', methods=['GET'])
  def go():
      def fun(item):
          time.sleep(2)
          item.value += 1
          db.session.commit()
      thr = threading.Thread(target=fun, args=(item,))
      # thr.daemon = True
      thr.start()
      return redirect(url_for('view'))
  
  @app.route('/view', methods=['GET'])
  def view(): return str(Item.query.get(1).value)
  
  app.run(host='0.0.0.0', port=8080, debug=True)
  </code></pre>
  
  <p>My expectation was that the item's value would be asynchronously updated after two seconds (when the <code>fun</code> completes), and that additional requests to <code>/view</code> would reveal the updated value. But this never occurs. I am not an expert on what is going on in the threading module; am I missing something?</p>
  
  <p>I have tried setting <code>thr.daemon=True</code> as pointed out in some posts; but that is not it. The closest SO post I have found is <a href="https://stackoverflow.com/questions/41580029/using-flask-sqlalchemy-from-worker-threads">this one</a>; that question does not have a minimal and verifiable example and has not been answered.</p>