2015年3月31日星期二

asyncio

上年寫咗一段code攞Hacker News 主題,跟住試改用requests,簡化如下:

import concurrent.futures
import requests

URL = 'https://hacker-news.firebaseio.com/v0/'

def get_hn_item(item_no):
    r = requests.get('{}item/{}.json'.format(URL, item_no))
    return r.json()

if __name__ == '__main__':
    r = requests.get(URL + 'topstories.json')
    toplist = r.json()[:10]
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for c, i in enumerate(executor.map(get_hn_item, toplist), 1):
            print('{:>3}: {}'.format(c, i['title']))

其實冇乜點簡化到,只係方便過用urllib少少,於是試吓改用Python 3.4內置的asyncio,然後再裝aiohttp,不用開thread或process,再改良一下:

有關asyncio和aiohttp的tutorial不多,較難學習。

沒有留言:

發佈留言