2012-05-01 4 views
1

클라이언트 (Kenneth Reitz 우수 requests 라이브러리)에 일부 콘텐츠를 스트리밍하려고하는 서버가 있습니다 - (아래 코드는 toastdriven.com의 소품). 브라우저에서는 예상대로 작동합니다. 왜이 HTTP 스트리밍이 예상대로 작동하지 않습니까?

from gevent import monkey 
monkey.patch_all() 

import datetime 
import time 
from gevent import Greenlet 
from gevent import pywsgi 
from gevent import queue 

import json 

def current_time(body): 
    current = start = datetime.datetime.now() 
    end = start + datetime.timedelta(seconds=60) 

    while current < end: 
     current = datetime.datetime.now() 
     message = json.dumps({'time': current.strftime("%Y-%m-%d %I:%M:%S")}) 
     body.put(message) 
     time.sleep(1) 

    body.put('</body></html>') 
    body.put(StopIteration) 

def handle(environ, start_response): 
    start_response('200 OK', [('Content-Type', 'text/html')]) 
    body = queue.Queue() 
    g = Greenlet.spawn(current_time, body) 
    return body 

server = pywsgi.WSGIServer(('127.0.0.1', 1234), handle) 
print "Serving on http://127.0.0.1:1234..." 
server.serve_forever() 

그리고 클라이언트 :

import sys 
import requests 
import json 

my_config = {'verbose': sys.stdout} 
r = requests.get('http://127.0.0.1:1234/', config=my_config) 

for line in r.iter_lines(): 
    print json.loads(line) 

내가 그나마 터미널 (OSX)에서 보여주는 'json으로 라인이 arent 이유를 이해'. Ctrl-C를 누르면 응답이 화면에 덤프됩니다.

내가 할 경우 예상대로

for line in r.iter_content() 

는 내가 JSON을 얻을, 각 행의 문자, 스트리밍.

아이디어가 있으십니까?

+0

실제로 서버 측 오류가 발생합니다. (WSGIServer는 대기열을 좋아하지 않습니다.) Python과 Gevent의 버전을 사용 하시겠습니까? – brice

+0

Gevent는 '0.13.7', Python 2.7.1 (r271 : 86832, 2011 년 6 월 16 일, 16:59:05) –

+0

감사합니다. Gevent를 업그레이드해야했습니다. – brice

답변

0

클라이언트가 버퍼링 된 터미널 창에서 실행 중일 가능성이 큽니다. 각 인쇄 후에 sys.stdout.flush()을 추가하여 출력 버퍼를 비우십시오.

+0

물론 - 제이 suis bonehead :) –

+0

그게 나를 위해 문제를 해결하지 않습니다. 내가 stdout 플러시 경우에도 동일한 동작을 얻을. – brice

관련 문제