我在為我的應用程序實現 Flask-MQTT 庫而苦苦掙扎。SQLAlchemy 等工作正常,但 flask-mqtt 拋出錯誤AttributeError: module 'app.mqtt' has no attribute 'init_app'。在 Flask-MQTT 的官方文檔中,他們以相同的方式構建了 create_app() 方法(https://flask-mqtt.readthedocs.io/en/latest/usage.html)如果有人可以幫助我,那就太好了!非常感謝__init__.pyfrom flask import Flaskfrom flask_restful import Apifrom flask_mqtt import Mqttfrom flask_sqlalchemy import SQLAlchemyfrom flask_marshmallow import Marshmallowfrom flask_jwt_extended import JWTManagermqtt = Mqtt()api = Api()db = SQLAlchemy()ma = Marshmallow()jwt = JWTManager()def create_app(config): app = Flask(__name__) app.config.from_object(config.DevelopmentConfig) mqtt.init_app(app) db.init_app(app) api.init_app(app) ma.init_app(app) jwt.init_app(app) return appfrom app.mqtt import mqttclient運行.pyfrom app import create_appimport configfrom flask_migrate import Migrateapp = create_app(config)migrate = Migrate(app, db)app.config['MQTT_BROKER_URL'] = 'hivemq'app.config['MQTT_BROKER_PORT'] = 1883app.config['MQTT_USERNAME'] = ''app.config['MQTT_PASSWORD'] = ''app.config['MQTT_KEEPALIVE'] = 5app.config['MQTT_TLS_ENABLED'] = Falseif __name__ == '__main__': app.run(host='0.0.0.0', port=5003, threaded=True)錯誤:mqttservice | Traceback (most recent call last):mqttservice | File "run.py", line 5, in <module>mqttservice | app = create_app(config)mqttservice | File "/code/app/__init__.py", line 18, in create_appmqttservice | mqtt.init_app(app)mqttservice | AttributeError: module 'app.mqtt' has no attribute 'init_app'
1 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
在那個代碼片段中,mqtt
有兩層意思。第一個是分配的變量
mqtt = Mqtt()
第二個是命名空間(模塊)
from app.mqtt import mqttclient
告訴在錯誤中
AttributeError: module 'app.mqtt' has no attribute 'init_app'
這是因為導入覆蓋了初始值,所以到那時,這.init_app()
不是mqtt
您所期望的。
您將不得不更改其中一個名稱。
添加回答
舉報
0/150
提交
取消