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

Question:

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
server1:

app = Flask(__name__)

api = Api(app)

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

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):
    @staticmethod
    def count():
        count = Value.query.count()
        return count

server2:

app2 = Flask(__name__)

api2 = Api(app2)

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

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):
    @staticmethod
    def count():
        count = Value2.query.count()
        return count

masternode:

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

app.app_context().push()
app2.app_context().push()

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

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ДомашкаFlaskTestmasternode.py", line 15, in <module>
    c1 = Value.query.count()
         ^^^^^^^^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagessqlalchemyormquery.py", line 3175, in count
    return self._from_self(col).enable_eagerloads(False).scalar()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagessqlalchemyormquery.py", line 2892, in scalar
    ret = self.one()
          ^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagessqlalchemyormquery.py", line 2869, in one
    return self._iter().one()
           ^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagessqlalchemyormquery.py", line 2915, in _iter
    result = self.session.execute(
             ^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagessqlalchemyormsession.py", line 1702, in execute
    bind = self.get_bind(**bind_arguments)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemysession.py", line 61, in get_bind
    engines = self._db.engines
              ^^^^^^^^^^^^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 629, in engines
    return self._app_engines[app]
           ~~~~~~~~~~~~~~~~~^^^^^
  File "C:UsersSergioAppDataLocalProgramsPythonPython311Libweakref.py", line 415, in __getitem__
    return self.data[ref(key)]
           ~~~~~~~~~^^^^^^^^^^
KeyError: <weakref at 0x000001E85C863330; to 'Flask' at 0x000001E8397750D0>
Asked By: Sergio

||

Answers:

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)
    time.sleep(1)
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.