[PYTHON] Python 및 Flask로 데이터 스트리밍
PYTHONPython 및 Flask로 데이터 스트리밍
나는 플라스크의 스트리밍을 사용하는 방법을 알아낼 수 없습니다. 내 코드는 다음과 같습니다.
@app.route('/scans/')
def scans_query():
url_for('static', filename='.*')
def generate():
yield render_template('scans.html')
for i in xrange(50):
sleep(.5)
yield render_template('scans.html', **locals())
return Response(stream_with_context(generate()))
및 내 템플릿 :
<p>{% i %}</p>
나는 페이지에서 반 초마다 바뀌는 카운터를보고 싶다. 대신, 내가 얻은 가장 가까운 것은 다음 줄에 각 번호를 인쇄하는 페이지입니다.
해결법
-
==============================
1.페이지의 기존 콘텐츠를 바꾸려면 javascript가 필요합니다. 즉, 보내거나 긴 폴링, 웹 소켓 등을 사용하여 요청을 보내거나 만들 수 있습니다. 서버 보내기 이벤트를 사용하는 방법은 여러 가지가 있습니다.
페이지의 기존 콘텐츠를 바꾸려면 javascript가 필요합니다. 즉, 보내거나 긴 폴링, 웹 소켓 등을 사용하여 요청을 보내거나 만들 수 있습니다. 서버 보내기 이벤트를 사용하는 방법은 여러 가지가 있습니다.
#!/usr/bin/env python import itertools import time from flask import Flask, Response, redirect, request, url_for app = Flask(__name__) @app.route('/') def index(): if request.headers.get('accept') == 'text/event-stream': def events(): for i, c in enumerate(itertools.cycle('\|/-')): yield "data: %s %d\n\n" % (c, i) time.sleep(.1) # an artificial delay return Response(events(), content_type='text/event-stream') return redirect(url_for('static', filename='index.html')) if __name__ == "__main__": app.run(host='localhost', port=23423)
static / index.html의 위치 :
<!doctype html> <title>Server Send Events Demo</title> <style> #data { text-align: center; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> if (!!window.EventSource) { var source = new EventSource('/'); source.onmessage = function(e) { $("#data").text(e.data); } } </script> <div id="data">nothing received yet</div>
연결이 끊어지면 브라우저는 기본적으로 3 초 안에 다시 연결됩니다. 아무것도 보낼 서버가 없으면 서버는 404를 반환하거나 다음 요청에 대한 응답으로 'text / event-stream'콘텐츠 유형 이외의 것을 보낼 수 있습니다. 서버에 더 많은 데이터가 있더라도 클라이언트 측에서 중지하려면 source.close ()를 호출 할 수 있습니다.
참고 : 스트림이 무한대가 아닌 경우 다른 기술 (SSE 아님)을 사용하여 자바 스크립트 스 니펫을 전송하여 텍스트를 대체하십시오 (무한
#!/usr/bin/env python import time from flask import Flask, Response app = Flask(__name__) @app.route('/') def index(): def g(): yield """<!doctype html> <title>Send javascript snippets demo</title> <style> #data { text-align: center; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> <div id="data">nothing received yet</div> """ for i, c in enumerate("hello"): yield """ <script> $("#data").text("{i} {c}") </script> """.format(i=i, c=c) time.sleep(1) # an artificial delay return Response(g()) if __name__ == "__main__": app.run(host='localhost', port=23423)
나는 여기에 HTML을 인라 인하여 더 이상 아무것도 없다는 것을 보여 주었다. 위와 같지만 템플릿을 사용하는 방법은 다음과 같습니다.
#!/usr/bin/env python import time from flask import Flask, Response app = Flask(__name__) def stream_template(template_name, **context): # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates app.update_template_context(context) t = app.jinja_env.get_template(template_name) rv = t.stream(context) # uncomment if you don't need immediate reaction ##rv.enable_buffering(5) return rv @app.route('/') def index(): def g(): for i, c in enumerate("hello"*10): time.sleep(.1) # an artificial delay yield i, c return Response(stream_template('index.html', data=g())) if __name__ == "__main__": app.run(host='localhost', port=23423)
where templates / index.html :
<!doctype html> <title>Send javascript with template demo</title> <style> #data { text-align: center; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> <div id="data">nothing received yet</div> {% for i, c in data: %} <script> $("#data").text("{{ i }} {{ c }}") </script> {% endfor %}
-
==============================
2.그런 템플릿을 사용한다면 여기에 주어진 stream_template 함수를 사용해야 할 것입니다 : http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
그런 템플릿을 사용한다면 여기에 주어진 stream_template 함수를 사용해야 할 것입니다 : http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
나는 이것을 테스트하지 않았지만, 다음과 같이 보일 수있다.
def stream_template(template_name, **context): app.update_template_context(context) t = app.jinja_env.get_template(template_name) rv = t.stream(context) rv.enable_buffering(5) return rv @app.route('/scans/') def scans_query(): url_for('static', filename='.*') def generate(): for i in xrange(50): sleep(.5) yield i return Response(stream_template('scans.html', i=generate()))
from https://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask by cc-by-sa and MIT license
'PYTHON' 카테고리의 다른 글
[PYTHON] ctypes에 C ++ 클래스를 사용하는 방법? (0) | 2018.10.10 |
---|---|
[PYTHON] 파이썬에서 깨진 파이프 (SIGPIPE)를 처리하는 방법은 무엇입니까? (0) | 2018.10.10 |
[PYTHON] Python으로 파일의 마지막 x 줄을 검색하는 가장 효율적인 방법 (0) | 2018.10.10 |
[PYTHON] MAPI를 통해 Python으로 Outlook에서 전자 메일 읽기 (0) | 2018.10.10 |
[PYTHON] Pythons timeit으로 성능을 테스트하기 위해 코드 세그먼트를 어떻게 시간을 잴 수 있습니까? (0) | 2018.10.10 |