我正在构建一个解决方案,该解决方案依赖于来自现场IOT设备的发布/订阅事件来启动一些处理。出于我的目的,我使用Flask来运行我的主应用程序。然后我运行mqtt Client连接到MQTT服务器并监听事件。
当我使用python app.py
运行我的主Flask app.py时,它启动Flask服务和MQTT客户端。但是,当我尝试使用gunicorn运行时,它只启动Flask服务但不启动MQTT客户端。
我可以使用什么生产等级服务(如果不是gunicorn)来运行这两种服务以及如何使用它?
import logging, json, requests, os
import paho.mqtt.client as mqtt
from flask import Flask, request, url_for
from flask_restful import reqparse, abort, Api, Resource
from logging.handlers import SysLogHandler
from logging import StreamHandler
from flask.ext.superadmin import Admin, BaseView, model
from redis import Redis
from rq import Queue
from task import Task
from dateutil.relativedelta import relativedelta
from datetime import datetime, date
..
..
from commons import db, bootstrap
app = Flask(__name__)
api = Api(app)
bootstrap.bootstrap_app(app)
#Setup (Redis) Queue store
q = Queue(connection=Redis())
#Intialize task instance
task = Task(app)
..
...
@app.before_request
def log_request_info():
app.logger.debug('Headers: %s', request.headers)
app.logger.debug('Body: %s', request.get_data())
#API resource routing
api.add_resource(Test, '/test')
def session_report(client, userdata, message):
print message.topic, message.payload
# Redirect to session_report endpoint
with app.test_request_context():
url = 'http://localhost:5000'+url_for('sessionreport', _external=False)
headers = {'content-type': 'application/json'}
response = requests.request("POST", url, data=message.payload,
headers=headers)
def process_ack(client, userdata, message):
try:
user = User()
user.update_account(account_number=next(iter(json.loads(message.payload))))
except Exception, e:
print e
def publish_accounts(client):
user_obj = User()
users = {user.id: user.account_number for user in user_obj.get_users()}
client.publish('accounts', payload=json.dumps(users), qos=1, retain=True)
# paho callbacks
def on_connect(client, userdata, flags, rc):
print "CONNECTED!", str(rc)
# Subscribe to topis(s) here
client.subscribe("mine/#")
client.subscribe("session/#")
client.subscribe("ack")
# Add callbacks to subscribed topics
client.message_callback_add("session/#", session_report)
client.message_callback_add("ack", process_ack)
# Publish latest list of accounts
publish_accounts(client)
def on_subscribe(client, userdata, mid, granted_qos):
print "Subscribed: ", str(mid), str(granted_qos)
def on_message(client, userdata, msg):
print msg.topic, msg.payload
def on_publish(client, userdata, mid):
print "PUBLISHED!"
app.logger.info('PUBLISHED : {} -- {}'.format(mid, userdata))
if __name__ == '__main__':
handler = StreamHandler() #SysLogHandler()
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)
client = mqtt.Client()
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()
app.run(debug=True, host='0.0.0.0', port=5000)
答案 0 :(得分:0)
Flask只是Python的一个微框架。 如果你想通过python同时运行多方法,你需要使用多线程编程。
我读了一些Flask文档,发现Flask支持多线程并发。
试试:
app.run(host='0.0.0.0',port=5000,debug=True, threaded = True)