Created
March 6, 2018 03:13
-
-
Save laixintao/cb03f0b01bfd30f93337a6497f27ee45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import signal | |
import sys | |
import asyncio | |
import aiohttp | |
import json | |
loop = asyncio.get_event_loop() | |
client = aiohttp.ClientSession(loop=loop) | |
async def get_json(client, url): | |
async with client.get(url) as response: | |
assert response.status == 200 | |
return await response.read() | |
async def get_reddit_top(subreddit, client): | |
print("start get json from {}".format(subreddit)) | |
data1 = await get_json(client, 'https://www.reddit.com/r/' + subreddit + '/top.json?sort=top&t=day&limit=5') | |
print("{} arrived".format(subreddit)) | |
j = json.loads(data1.decode('utf-8')) | |
for i in j['data']['children']: | |
score = i['data']['score'] | |
title = i['data']['title'] | |
link = i['data']['url'] | |
print(str(score) + ': ' + title + ' (' + link + ')') | |
print('DONE:', subreddit + '\n') | |
def signal_handler(signal, frame): | |
loop.stop() | |
client.close() | |
sys.exit(0) | |
signal.signal(signal.SIGINT, signal_handler) | |
for topic in ("python", "programming", "compsci"): | |
print("Start ensure future: {}".format(topic)) | |
asyncio.ensure_future(get_reddit_top(topic, client)) | |
loop.run_forever() |
Author
laixintao
commented
Mar 6, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment