python - 同时从 Rabbitmq 接收日志并运行您的 flask 应用程序

标签 python multithreading flask rabbitmq rabbitmqctl

我已经安装了rabbitmq并且可以正常工作,我知道如何接收日志但不知道如何使用flask将其显示给UI。

flask 应用程序.py

from flask import Flask
from threading import Thread
app = Flask(__name__)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                     type='fanout')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='logs',
               queue=queue_name)

print('[*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
    print(body)

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

thread = Thread(channel.start_consuming())
thread.start()

@app.route('/')
def index():
    return 'hi'

我不知道如何使用多线程来运行 Flask 应用程序并不断从队列中接收日志。

最佳答案

您的 Flask 应用程序,这里是主线程,运行的时间或请求量由您的 uwsgi 或您用来运行它的任何其他工具决定。当主进程停止时,很可能是正常关闭 amqp 连接的错误时间。

此外,您的应用程序可能有多个实例同时运行(想想 uwsgi processes ),因此您会在每个工作程序/进程上获得一些日志。

这里的明智方法是将这两件事分开。在 Web 应用程序范围之外为您的日志运行消费者进程,即:使用 supervisord。

关于python - 同时从 Rabbitmq 接收日志并运行您的 flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236802/

相关文章:

Python 空闲 : how to run the whole script as it is always stopping at some point

python - 根据另一个数据框选定的行和列部分更新数据框

python - Flask jsonify 在新行打印结果

javascript - Flask 返回重定向在删除后不起作用

python - 如果索引是时间戳,如何从 pandas 生成列表

python - 如果所有列彼此相等,如何从数据框中删除行?

multithreading - 具有隐藏窗口的线程的线程消息循环?

c - 与 Linux 相比,为什么 pthread_mutex 在 Mac OS X 上的性能如此糟糕?

Python 请求 URLLib3 连接池大小

android - 使用Retrofit将音频文件上传到Flask API