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

问题描述

我试图用Flask的微型web框架上的服务器推送功能来构建一个小型站点,但我不知道是否有一个框架可以直接使用。

我用,但在当前版本中,它似乎无法与一起使用,并且Juggernaut已被弃用最近。



有人对我的案子有什么建议吗?

解决方案

查看。 Server-Sent Events是一个
浏览器API,可以让你保持打开你的服务器的套接字,订阅一个
的更新流。欲了解更多信息,请阅读的Alex MacCaw(作者为
Juggernaut)以及为什么更简单的
服务器发送的事件在manny情况下是比
Websockets更好的工具。



协议非常简单。只需将mimetype text / event-stream 添加到
响应中。浏览器将保持连接打开并侦听更新。从服务器发送的事件
是以 data:开头的一行文本,后面是换行符。

  data:这是一个简单的消息
< blank line>

如果您想交换结构化数据,只需将您的数据转储为json并通过线路发送json 。

一个优点是你可以在Flask中使用SSE而不需要额外的
服务器。 github上有一个简单的,
使用redis作为pub / sub后端。

  def event_stream():
pubsub = red.pubsub()
pubsub.subscribe ')
为pubsub.listen()中的消息:
打印消息
产生'data:%s\\\
\\\
'消息['data']


@ app.route('/ post',methods = ['POST'])
def post():
message = flask.request.form ['message']
user = flask.session.get('user','anonymous')
now = datetime.datetime.now()。replace(微秒= 0).time()
红色。发布('chat',u'[%s]%s:%s'%(now.isoformat(),user,message))


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

您不需要使用gunicron来运行
示例应用程序。只要确保在运行应用程序时使用线程,因为
,否则SSE连接将阻塞您的开发服务器:

pre $ if __name__ =='__main__':
app.debug = True
app.run(threaded = True)

在客户端,您只需要一个Javascript处理程序函数,当从服务器推送新的
消息时将调用它。

  var source = new EventSource('/ stream'); 
source.onmessage = function(event){
alert(event.data);
};

服务器发送的事件



  • I am trying to build a small site with the server push functionality on Flask micro-web framework, but I did not know if there is a framework to work with directly.

    I used Juggernaut, but it seems to be not working with redis-py in current version, and Juggernaut has been deprecated recently.

    Does anyone has a suggestion with my case?

    解决方案

    Have a look at Server-Sent Events. Server-Sent Events is abrowser API that lets you keep open a socket to your server, subscribing to astream of updates. For more Information read Alex MacCaw (Author ofJuggernaut) post on why he kills juggernaut and why the simplerServer-Sent Events are in manny cases the better tool for the job thanWebsockets.

    The protocol is really easy. Just add the mimetype text/event-stream to yourresponse. The browser will keep the connection open and listen for updates. An Eventsent from the server is a line of text starting with data: and a following newline.

    data: this is a simple message
    <blank line>
    

    If you want to exchange structured data, just dump your data as json and send the json over the wire.

    An advantage is that you can use SSE in Flask without the need for an extraServer. There is a simple chat application example on github whichuses redis as a pub/sub backend.

    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('/post', methods=['POST'])
    def post():
        message = flask.request.form['message']
        user = flask.session.get('user', 'anonymous')
        now = datetime.datetime.now().replace(microsecond=0).time()
        red.publish('chat', u'[%s] %s: %s' % (now.isoformat(), user, message))
    
    
    @app.route('/stream')
    def stream():
        return flask.Response(event_stream(),
                              mimetype="text/event-stream")
    

    You do not need to use gunicron to run theexample app. Just make sure to use threading when running the app, becauseotherwise the SSE connection will block your development server:

    if __name__ == '__main__':
        app.debug = True
        app.run(threaded=True)
    

    On the client side you just need a Javascript handler function which will be called when a newmessage is pushed from the server.

    var source = new EventSource('/stream');
    source.onmessage = function (event) {
         alert(event.data);
    };
    

    Server-Sent Events are supported by recent Firefox, Chrome and Safari browsers.Internet Explorer does not yet support Server-Sent Events, but is expected to support them inVersion 10. There are two recommended Polyfills to support older browsers

    这篇关于如何在Flask框架中实现服务器推送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-29 20:12
    查看更多