python异步httprequest [英] python asynchronous httprequest

查看:42
本文介绍了python异步httprequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中使用 twitter 搜索网络服务.我想调用一个网络服务,如:

I am trying to use twitter search web service in python. I want to call a web service like:

http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed

来自我的 python 程序.

from my python program.

谁能告诉我

  1. 如何在python中使用xmlhttprequst对象

  1. how to use xmlhttprequst object in python

如何向它传递参数,以及

how to pass parameters to it, and

如何获取字典中的数据.

how to get the data in dictionary.

这是我的尝试:

import urllib
import sys
url = "http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed"
urlobj = urllib.urlopen(url)
data = urlobj.read()
print data

谢谢.

推荐答案

你不需要异步httprequest"来使用twitter搜索api:

You don't need "asynchronous httprequest" to use twitter search api:

import json
import urllib
import urllib2

# make query
query = urllib.urlencode(dict(q="blue angel", rpp=5, include_entities=1,
                              result_type="mixed"))  
# make request
resp = urllib2.urlopen("http://search.twitter.com/search.json?" + query)

# make dictionary (parse json response)
d = json.load(resp)

可能有几个库为这些 http 请求提供了一个很好的 OO 接口.

There are probably several libraries that provide a nice OO interface around these http requests.

要同时发出多个请求,您可以使用 gevent:

To make multiple requests concurrently you could use gevent:

import gevent
import gevent.monkey; gevent.monkey.patch_all() # patch stdlib

import json
import urllib
import urllib2

def f(querystr):
    query = urllib.urlencode(dict(q=querystr, rpp=5, include_entities=1,
                                  result_type="mixed"))
    resp = urllib2.urlopen("http://search.twitter.com/search.json?" + query)
    d = json.load(resp)
    print('number of results %d' % (len(d['results']),))

jobs = [gevent.spawn(f, q) for q in ['blue angel', 'another query']]
gevent.joinall(jobs) # wait for completion

这篇关于python异步httprequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆