我在为我的应用程序实现 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
提交
取消