Mic*_*tak 19 python rabbitmq flask socket.io
我在通过SocketIO从RabbitMQ向用户发送消息时遇到问题.
我有与SocketIO集成的 Flask应用程序.目前的用户流程似乎如此
问题是我无法设置RabbitMQ监听器,它通过SocketIO将消息转发给浏览器.每次我得到不同的错误.主要是连接关闭,或者我在应用程序上下文之外工作.
我尝试了很多方法,这是我的最后一个方法.
# callback
def mq_listen(uid):
rabbit = RabbitMQ()
def cb(ch, method, properties, body, mq=rabbit):
to_return = [0] # mutable
message = Message.load(body)
to_return[0] = message.get_message()
emit('report_part', {"data": to_return[0]})
rabbit.listen('results', callback=cb, id=uid)
# this is the page, which user reach
@blueprint.route('/report_result/<uid>', methods=['GET'])
def report_result(uid):
thread = threading.Thread(target=mq_listen, args=(uid,))
thread.start()
return render_template("property/report_result.html", socket_id=uid)
Run Code Online (Sandbox Code Playgroud)
其中rabbit.listen方法是抽象的:
def listen(self, queue_name, callback=None, id=None):
if callback is not None:
callback_function = callback
else:
callback_function = self.__callback
if id is None:
self.channel.queue_declare(queue=queue_name, durable=True)
self.channel.basic_qos(prefetch_count=1)
self.consumer_tag = self.channel.basic_consume(callback_function, queue=queue_name)
self.channel.start_consuming()
else:
self.channel.exchange_declare(exchange=queue_name, type='direct')
result = self.channel.queue_declare(exclusive=True)
exchange_name = result.method.queue
self.channel.queue_bind(exchange=queue_name, queue=exchange_name, routing_key=id)
self.channel.basic_consume(callback_function, queue=exchange_name, no_ack=True)
self.channel.start_consuming()
Run Code Online (Sandbox Code Playgroud)
这导致了
RuntimeError: working outside of request context
Run Code Online (Sandbox Code Playgroud)
我会很高兴任何提示或使用示例.
非常感谢
错误消息表明这是 Flask 问题。在处理请求时,Flask 会设置一个上下文,但由于您使用的是线程,因此该上下文会丢失。当需要它时,它不再可用,因此 Flask 会给出“在请求上下文之外工作”错误。
解决此问题的常见方法是手动提供上下文。文档中有一个关于此的部分:http://flask.pocoo.org/docs/1.0/appcontext/#manually-push-a-context
您的代码不显示 socketio 部分。但我想知道使用像flask-socketio这样的东西是否可以简化一些东西......(https://flask-socketio.readthedocs.io/en/latest/)。我将在后台打开 RabbitMQ 连接(最好一次)并使用该emit函数将任何更新发送到连接的 SocketIO 客户端。
| 归档时间: |
|
| 查看次数: |
2476 次 |
| 最近记录: |