반응형
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
www.w3schools.com/html/html5_serversentevents.asp
developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
flask-sse.readthedocs.io/en/latest/advanced.html
developer.mozilla.org/en-US/docs/Web/API/EventSource
github.com/jakubroztocil/chat/blob/master/app.py
www.youtube.com/watch?v=4HlNv1qpZFY
github.com/coderspage/flask-sse/blob/main/index.html
spoqa.github.io/2014/01/20/sse.html
stackoverflow.com/questions/12232304/how-to-implement-server-push-in-flask-framework
github.com/singingwolfboy/flask-sse
github.com/boppreh/server-sent-events
medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56
더보기
반응형
'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 |