[Solved] RuntimeError: No application found. Either work inside a view function or push an application contex

Python + Flash + Flash Sqlalchemy to realize MySQL database operation

Write test cases in Python to realize MySQL query

The test cases are as follows:

class MySQLTest(unittest.TestCase):

  def test_queryAll(self):
      uas = db.session.query(UserAgent).all()
      self.assertIsNotNone(uas)

      for ua in uas:
        print("\n")
        print(ua)


if __name__ == '__main__':
  unittest.main()

1、 Problem description

Error message below

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

If no application is found, either work in the view function or push the application context

The first reaction should be related to writing test cases in Java Web applications, and the application context cannot be found


2、 Problem analysis

The test case starts a thread to execute database operation separately, which is independent of the flash application. It is unable to obtain the configuration information of the flash application context (including database connection information), so it is necessary to push the application context (inject context object)

This is why it works in the view function, which runs in the web container of flash.


3、 Solution

Python uses the with statement to manage context

The with statement is essentially context management
1. Context management protocol. Inclusion method__ enter__() And exit (), which support the protocol object to implement these two methods
2. The context manager defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block
3. Execute when entering the context__ enter__ Method. If the as var statement is set, the VaR variable accepts__ enter__() Method returns a value
4. If an exception occurs during runtime, exit the context manager. Call manager__ exit__ method.

Push the application context, that is, at the top where the thread starts executing code,
add with app.app_ context():

class MySQLTest(unittest.TestCase):

  def test_queryAll(self):
    with app.app_context():
      uas = db.session.query(UserAgent).all()
      self.assertIsNotNone(uas)

      for ua in uas:
        print("\n")
        print(ua)


if __name__ == '__main__':
  unittest.main()

4、 Result verification

Add with app.app_Context():
just write your own program logic, and the test case runs successfully

Read More: