본문 바로가기

Python

[PYTHON] SSE (feat. Flask)(Server-Sent Events)

반응형

app.py

#!/usr/bin/env python
import datetime
import flask
import redis


app = flask.Flask(__name__)
app.secret_key = 'asdf'
red = redis.StrictRedis()


def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    # TODO: handle client disconnection.
    for message in pubsub.listen():
        print (message)
        if message['type']=='message':
            yield 'data: %s\n\n' % message['data'].decode('utf-8')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'POST':
        flask.session['user'] = flask.request.form['user']
        return flask.redirect('/')
    return '<form action="" method="post">user: <input name="user">'


@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))
    return flask.Response(status=204)


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


@app.route('/')
def home():
    if 'user' not in flask.session:
        return flask.redirect('/login')
    return """
        <!doctype html>
        <title>chat</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <style>body { max-width: 500px; margin: auto; padding: 1em; background: black; color: #fff; font: 16px/1.6 menlo, monospace; }</style>
        <p><b>hi, %s!</b></p>
        <p>Message: <input id="in" /></p>
        <pre id="out"></pre>
        <script>
            function sse() {
                var source = new EventSource('/stream');
                var out = document.getElementById('out');
                source.onmessage = function(e) {
                    // XSS in chat is fun (let's prevent that)
                    out.textContent =  e.data + '\\n' + out.textContent;
                };
            }
            $('#in').keyup(function(e){
                if (e.keyCode == 13) {
                    $.post('/post', {'message': $(this).val()});
                    $(this).val('');
                }
            });
            sse();
        </script>
    """ % flask.session['user']


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

 출처: 

github.com/jakubroztocil/chat/blob/master/app.py

 

jakubroztocil/chat

A simple chat app created to experiment with Redis, Gevent, Flask & Server-Sent Events. - jakubroztocil/chat

github.com

www.w3schools.com/html/html5_serversentevents.asp

 

HTML Server-Sent Events API

HTML SSE API Server-Sent Events (SSE) allow a web page to get updates from a server. Server-Sent Events - One Way Messaging A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page wou

www.w3schools.com

developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

 

Using server-sent events - Web APIs | MDN

Using server-sent events Developing a web application that uses server-sent events is straightforward. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of h

developer.mozilla.org

flask-sse.readthedocs.io/en/latest/advanced.html

 

Advanced Usage — Flask-SSE 0.2.1 documentation

Channels Sometimes, you may not want all events to be published to all clients. For example, a client that cares about receiving the latest updates in their social network probably doesn’t care about receiving the latest statistics about how many users a

flask-sse.readthedocs.io

 

developer.mozilla.org/en-US/docs/Web/API/EventSource

 

EventSource - Web APIs | MDN

EventSource The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by cal

developer.mozilla.org

github.com/jakubroztocil/chat/blob/master/app.py

 

jakubroztocil/chat

A simple chat app created to experiment with Redis, Gevent, Flask & Server-Sent Events. - jakubroztocil/chat

github.com

www.youtube.com/watch?v=4HlNv1qpZFY

github.com/coderspage/flask-sse/blob/main/index.html

 

coderspage/flask-sse

Contribute to coderspage/flask-sse development by creating an account on GitHub.

github.com

spoqa.github.io/2014/01/20/sse.html

 

SSE를 이용한 실시간 웹앱

HTML5의 표준안으로 권고되어있는 Server-Sent Events에 대해 알아보고 이를 이용하여 실시간 웹앱을 만들어 봅시다.

spoqa.github.io

stackoverflow.com/questions/12232304/how-to-implement-server-push-in-flask-framework

 

How to implement server push in Flask framework?

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 seem...

stackoverflow.com

github.com/singingwolfboy/flask-sse

 

singingwolfboy/flask-sse

Server-Sent Events for Flask. Contribute to singingwolfboy/flask-sse development by creating an account on GitHub.

github.com

github.com/boppreh/server-sent-events

 

boppreh/server-sent-events

Python library for Server-Sent-Events. Contribute to boppreh/server-sent-events development by creating an account on GitHub.

github.com

medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56

 

Python and Server-sent Event

I have had the chance to work on an IoT project that used HTML5 Server-sent Event(SSE) in Python and here is why I thought Python is a…

medium.com

더보기

 

반응형