Strange error when trying to get data from database in another file


I was trying to get count of items in databases. Getting count with second database is working as planned, but the first one is giving me this error
KeyError: <weakref at 0x000001E85C863330; to "Flask" at 0x000001E8397750D0>
This program is a very simplified, but removed elements are working fine(Get, Post, Delete methods…)

So I have 3 files

app = Flask(__name__)

api = Api(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///emp.db'

db = SQLAlchemy(app)

class Value(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    value = db.Column(db.Integer, nullable=False)

class GetCount(Resource):
    def count():
        count = Value.query.count()
        return count


app2 = Flask(__name__)

api2 = Api(app2)

app2.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///emp2.db'

db2 = SQLAlchemy(app2)

class Value2(db2.Model):
    id = db2.Column(db2.Integer, primary_key=True)
    value = db2.Column(db2.Integer, nullable=False)

class GetCount2(Resource):
    def count():
        count = Value2.query.count()
        return count


import time
from server1 import app, Value
from server2 import app2, Value2


while True:
    c = Value.query.count()
    c2 = Value2.query.count()
    print(c, c2)

I was trying to start this program, but got the error mentioned above. But when I deleted
c = Value.query.count()
from masternode file I got expected result(1 1 1 1 and so on)

So I really don’t understand why one program is working and other is not when they are practically the same

Full error traceback:

Traceback (most recent call last):
  File "C:UsersSergioDesktopДомашка", line 15, in <module>
    c1 = Value.query.count()
  File "", line 3175, in count
    return self._from_self(col).enable_eagerloads(False).scalar()
  File "", line 2892, in scalar
    ret =
  File "", line 2869, in one
    return self._iter().one()
  File "", line 2915, in _iter
    result = self.session.execute(
  File "", line 1702, in execute
    bind = self.get_bind(**bind_arguments)
  File "", line 61, in get_bind
    engines = self._db.engines
  File "", line 629, in engines
    return self._app_engines[app]
  File "", line 415, in __getitem__
KeyError: <weakref at 0x000001E85C863330; to 'Flask' at 0x000001E8397750D0>
Asked By: Sergio



Flask uses app contexts to determine the current app, so queries for different apps should be run in their respective contexts.

Something like this ought to work:

while True:
    with app.app_context():
        c = Value.query.count()
    with app2.app_context:
        c2 = Value2.query.count()
    print(c, c2)
Answered By: snakecharmerb
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.