server.py
import gevent.monkey; gevent.monkey.patch_all()
import itertools
import json
import random
import time
import bottle
@bottle.get("/foo")
def foo():
for i in range(5):
o = {"i": i, "r": random.random()}
print 'sending: {}'.format(o)
yield json.dumps(o) + "\n"
time.sleep(1)
if __name__ == '__main__':
bottle.run(
host="localhost",
port=1234,
server="gevent"
)
client.py
import json
import pprint
import sys
import requests
def main(url):
print 'Reading from {}'.format(url)
for line in requests.get(url, stream=True).iter_lines(chunk_size=1):
pprint.pprint(json.loads(line))
print 'All done.'
if __name__ == '__main__':
main(sys.argv[1])
用法,
$ python server.py &
$ python client.py http://localhost:1234/foo