Flask更新到新版本后,现在我用的是 Flask2.2.2,会报这个错:
1 2 3 4 This typically means that you attempted to use functionality that needed to interface with the current application object in  some way. To solve this, set  up an application context with app.app_context().  See the documentation for  more information. 
以前用的旧版本没碰到这个问题。
这是我第2次碰到这个问题了。
第1次 数据库初始化的时候 第1次是数据库初始化的时候,原来在main函数中是这样写的,就报了这个错。
1 2 3 4 5 6 7 8 if  __name__ == '__main__' :              db.drop_all()          db.create_all()     app.run('0.0.0.0' , port=5000 )  
解决方法: 
改成下面这样就行了,加了句with app.app_context():
1 2 3 4 5 6 7 8 9 if  __name__ == '__main__' :         with  app.app_context():                  db.drop_all()                  db.create_all()     app.run('0.0.0.0' , port=5000 )  
关于app.run()这句的提醒,想解决看这篇文章:Python Flask使用WSGI server 
第2次 数据库插入数据的时候 用flask_sqlalchemy,进行数据库插入的时候,也报了这个错。
原来是这么写的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class  Record (db.Model ):    id  = db.Column(db.Integer, primary_key=True )     device_id = db.Column(db.String(80 ), unique=False , nullable=False )     temperature = db.Column(db.Float, nullable=False )     humidity = db.Column(db.Float, nullable=False )     pressure = db.Column(db.Float, nullable=False )     def  __init__ (self, device_id, temperature, humidity, pressure ):         self.device_id = device_id         self.temperature = temperature         self.humidity = humidity         self.pressure = pressure @mqtt_client.on_message() def  handle_mqtt_message (client, userdata, message ):    global  user_data                record = Record(**user_data)     print (record)     try :         db.session.add(record)         db.session.commit()     except  Exception as  e:         db.session.rollback()         print (e) 
改成下面这样,其实也是一样的,涉及到数据库写入的时候,套上with app.app_context()就行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @mqtt_client.on_message() def  handle_mqtt_message (client, userdata, message ):    global  user_data               with  app.app_context():         record = Record(**user_data)         print (record)         try :             db.session.add(record)             db.session.commit()         except  Exception as  e:             db.session.rollback()             print (e)