[英]How to run 2 servers from the same script in Python
I'm building a solution that depends on pub/sub events from IOT devices in the field to kick off some processing. 我正在构建一个解决方案,该解决方案依赖于现场IOT设备的发布/订阅事件来启动一些处理。 For my purposes, I'm using Flask as to run my main app.
就我的目的而言,我使用Flask as来运行我的主应用程序。 I then run the mqtt Client to connect to an MQTT server and listen for events.
然后,我运行mqtt客户端以连接到MQTT服务器并侦听事件。
When I run my main Flask app.py using python app.py
it starts both the Flask service and the MQTT Client. 当我使用
python app.py
运行我的主Flask app.py时, python app.py
同时启动Flask服务和MQTT客户端。 However, when I try to run with gunicorn, it only starts the the Flask service but does not start the MQTT Client. 但是,当我尝试与gunicorn一起运行时,它只会启动Flask服务,而不会启动MQTT Client。
What production grade service (if not gunicorn) can I use to have both these two services run and how to use it? 我可以使用哪种生产级服务(如果不是傻瓜)来同时运行这两项服务,以及如何使用它?
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)
Flask is just a microframework for Python. Flask只是Python的微框架。 if you want to run multi-method at the same time by python, you need to use multi-threading programming.
如果要通过python同时运行多方法,则需要使用多线程编程。
I read some more Flask document and found that Flask supports multithreaded concurrency. 我阅读了更多Flask文档,发现Flask支持多线程并发。
just try: 你试一试:
app.run(host='0.0.0.0',port=5000,debug=True, threaded = True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.