Trip: 给Requests加上协程,一百份网络请求一份时间

来源:互联网 发布:数据库文件类型 编辑:程序博客网 时间:2024/05/29 11:44

Trip 是一个协程的网络库,如 Requests 一般简单的操作,程序不再被网络阻塞。

兼容 Python 2.7+ 的所有版本,主流三大操作系统。

基于两大依赖包:TRIP: Tornado & Requests In Pair

感谢Tornado与Requests让想法可以快速变成现实,坦诚的说,这个项目我只做了一些简单的工作。

让协程变的简单

这是一个让协程变的简单的项目,你只需要这样:

import trip@trip.coroutinedef main():    r = yield trip.get('https://httpbin.org/get', auth=('user', 'pass'))    print(r.content)trip.run(main)

一百份请求一份时间

基于 Tornado 的协程让网络阻塞不再成为问题:(这里演示兼容用法)

import time, functoolsimport requests, tripdef timeit(fn):    start_time = time.time()    fn()    return time.time() - start_timeurl = 'http://httpbin.org/get'times = 10 # 100 changed for inland network delaydef fetch():    r = [requests.get(url) for i in range(times)]    return r@trip.coroutinedef async_fetch():    r = yield [trip.get(url) for i in range(times)]    raise trip.Return(r)print('Non-trip cost: %ss' % timeit(fetch))print('Trip cost: %ss' % timeit(functools.partial(trip.run, async_fetch)))# Result:# Non-trip cost: 17.90799999237s# Trip cost: 0.172300004959s

由于协程的特性,所有的等待时间重合在了一起。

你不需要每个请求开一个线程,主线程中一切也可以井然有序的进行。

可以想象如果你在写一个爬虫,这将节省多少时间!

让协程服务人类

基于 Requests 的操作方式让协程 HTTP 从未如此简单:(这里使用 Python3 演示async/await)

>>> async def main():...     global r...     r = await trip.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))...>>> trip.run(main)>>> r.status_code200>>> r.headers['content-type']'application/json'>>> r.encodingNone>>> r.textu'{"authenticated": true,...'>>> r.json(){u'authenticated': True, u'user': u'user'}

只要你有一些 Requests 基础就可以轻松使用 Trip,协程不再遥不可及。

重现了几乎所有 Requests 的操作,最大限度的减少了你的学习成本。

以一个爬虫为例

为了不打扰正常网站的运行,这里以httpbin.org作为目标网站。
设置 Cookies 模拟登陆,get 请求模拟爬取内容。

那么普通 Requests 是这样的:

import requestsurl = 'http://httpbin.org's = requests.Session()def fetch(times=10):    s.get('%s/cookies/set?name=value' % url)    r = [s.get('%s/get' % url) for i in range(times)]    print rfetch()

使用 Trip 以后就会变成这样:

import tripurl = 'http://httpbin.org's = trip.Session()@trip.coroutinedef fetch(times=10):    yield s.get('%s/cookies/set?name=value' % url)    r = yield [s.get('%s/get' % url) for i in range(times)]    print rtrip.run(fetch)

几乎不需要修改代码,爬虫就获得了协程的特性!

最后

爬虫耗时太久优化困难吗?
各种协程网络框架难以使用吗?
大型爬虫框架臃肿无法灵活定制吗?

试试Trip,你不会后悔的!