如何关闭Flask中的服务器发送事件连接

如何关闭Flask中的服务器发送事件连接

本文介绍了如何关闭Flask中的服务器发送事件连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面给出了一个使用node.js的答案。

):

<$ p ():
pubsub.subscribe('chat')
用于pubsub.listen()中的消息:$ b $ pubsub.subscribe('chat')
pubsub = red.pubsub
print message
yield'data:%s\\\
\\\
'%message ['data']

@ app.route('/ stream')
def stream():
return flask.Response(event_stream(),
mimetype =text / event-stream)

Flask向Redis发送一条新消息(锁定操作)稳定的,但是当Flask看到流终止时( StopIteration ,如果你不是Python的新手),它会返回。

  def event_stream():
pubsub = red.pubsub()
pubsub.subscribe('chat')
在pubsub.listen ():
if i_should_close_the_connection:
break
yield'data:%s\\\
\\\
'%message ['data']

@app。 route('/ stream')
def stream():
return flask.Response(event_stream(),
mimetype =text / event-stream)


The below has given an answer using node.js.

How to close a "Server-Sent Events"-connection on the server?

However, how to do the same thing in python Flask?

解决方案

Well, it depends on the architecture of your app.

Let me show you an example (see this code at https://github.com/jkbr/chat/blob/master/app.py):

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        print message
        yield 'data: %s\n\n' % message['data']

@app.route('/stream')
def stream():
    return flask.Response(event_stream(),
                          mimetype="text/event-stream")

Flask asks a new message to Redis (locking operation) steadily, but when Flask sees that streaming terminates (StopIteration, if you aren't new to Python), it returns.

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        if i_should_close_the_connection:
            break
        yield 'data: %s\n\n' % message['data']

@app.route('/stream')
def stream():
    return flask.Response(event_stream(),
                          mimetype="text/event-stream")

这篇关于如何关闭Flask中的服务器发送事件连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:32