简体   繁体   English

模仿Twitter的流API

[英]Imitating Twitter's Streaming API

Twitter implements a streaming API for serving tweets one at a time as JSON blobs. Twitter实现了一种流API ,可一次将一条推文作为JSON Blob提供。 Further, libraries such as Python's requests can consume from it like so, 此外,像Python的requests之类的库可以像这样从中使用,

import json
import requests

r = requests.get('http://httpbin.org/stream/20', stream=True)

for line in r.iter_lines():

    # filter out keep-alive new lines
    if line:
        print json.loads(line)

How might I implement, server-side, something that can be consumed the same way? 如何在服务器端实现可以以相同方式使用的东西? Ideally, using something like bottle ? 理想情况下,使用类似bottle东西?

One can aim to make a module that rolls streams of data based on a uri - without making it RESTful that is. 可以使一个模块基于uri滚动数据流,而无需使其成为RESTful。

For example //site.org/stream/40/ 例如//site.org/stream/40/

Theres several ways to communicate with an HTTP library like curl or requests. 与curl或请求之类的HTTP库进行通讯的方式有几种。 A basic approach would be to accept the recipient's POST data, store it in a database with a unique id and wait for a response. 一种基本方法是接受收件人的POST数据,将其存储在具有唯一ID的数据库中,然后等待响应。 And you can use a javascript's xhr to find out if the response is ready. 您可以使用javascript的xhr来确定响应是否准备就绪。

All in all on the backend it should be a python module whether you use django, bottle, etc. is your call. 总而言之,无论您使用的是django,bottle还是后端,它都应该是一个python模块。

Hope that helps. 希望能有所帮助。

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])

usage, 用法,

$ python server.py &
$ python client.py http://localhost:1234/foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM