简体   繁体   English

如何在Python中使用同一脚本运行2台服务器

[英]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.

相关问题 如何在任何地方使用像python这样的免费在线服务器每天同时运行python脚本? - How to use free online servers like python anywhere to run python script at the same time every day? 从同一脚本 Python 运行 2 个 web.py 服务器 - Running 2 web.py servers from the same script Python 如何从相同的python脚本运行.py和.exe文件 - how to run both a .py and a .exe file from the same python script 如何从python程序运行许多aiohttp服务器 - How run many aiohttp servers from python program 如何同时运行 2 个脚本 python? - How run 2 script python in same time? 如何使用bash脚本在不同端口同时运行两台flask服务器 - How to run two flask servers on different ports at the same time using bash script Python:如何从脚本中运行脚本? - Python: How to run a script from within a script? 如何同时运行多个eventlet服务器? - How to run multiple eventlet servers at the same time? 在 Python 中,如何同时从主脚本运行另一个 Python 脚本并在停止主脚本时将其关闭? - In Python, how can I run another Python script from the main script at the same time and close it when I stop the main script? 如何在一个python代码中运行两个服务器 - How to run two servers in one python code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM