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
www.velotio.com/engineering-blog/how-to-implement-server-sent-events-using-python-flask-and-react
How to Implement Server Sent Events Using Python Flask and React
www.velotio.com
자바스크립트는 어떻게 작동하는가: 웹소켓 및 HTTP/2 SSE
How JavaScript works: Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path
engineering.huiseoul.com
Spring Boot, SSE(Server-Sent Events)로 단방향 스트리밍 통신 구현하기
개요 Server-Sent Events (이하 SSE)는 HTTP 스트리밍을 통해 서버에서 클라이언트로 단방향의 Push Notification을 전송할 수 있는 HTML5 표준 기술이다. 이번 글에서는 Spring Boot에서 SSE를 이용한 단방향 스..
jsonobject.tistory.com
stackoverflow.com/questions/54326515/how-can-i-make-sse-with-python-django
How can I make SSE with Python (Django)?
I have two different pages, one (A) that displays data taken from a model object, and one (B) that changes its fields. I would like that when the post data is sent from B to the server, the server
stackoverflow.com
'Python' 카테고리의 다른 글
[Python] MySQL 쿼리 (0) | 2021.05.03 |
---|---|
[python] mysql query 수행이력 보기 (0) | 2021.04.30 |
[python] 제너레이터와 yield 알아보기 (0) | 2021.04.20 |
[PYTHON] class 정리 - 상속(inheritance) (0) | 2021.04.19 |
[PYTHON] 서버·개발 환경을 위한 config 분리하기 (0) | 2021.04.19 |