-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_async_ex1.py
76 lines (61 loc) · 2.5 KB
/
python_async_ex1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import requests
import aiohttp
import asyncio
import time
from key import key
start_time = time.time()
print("getting first contentDetails")
channel_id = 'UC-QDfvrRIDB6F0bIO4I4HkQ'
url = f'https://www.googleapis.com/youtube/v3/channels?id={channel_id}&key={key}&part=contentDetails'
r = requests.get(url)
print(r.json())
results = r.json()['items']
print(results)
playlist_id = results[0]['contentDetails']['relatedPlaylists']['uploads']
print('playlist_id is ' + playlist_id)
url = f'https://www.googleapis.com/youtube/v3/playlistItems?playlistId={playlist_id}&key={key}&part=contentDetails&maxResults=50'
video_ids = []
while True:
r = requests.get(url)
results = r.json()
if 'nextPageToken' in results:
nextPageToken = results['nextPageToken']
else:
nextPageToken = None
if 'items' in results:
for item in results['items']:
videoId = item['contentDetails']['videoId']
video_ids.append(videoId)
if nextPageToken:
url = f'https://www.googleapis.com/youtube/v3/playlistItems?playlistId={playlist_id}&pageToken={nextPageToken}&key={key}&part=contentDetails&maxResults=50'
else:
break
print('video_ids are '+ str(video_ids))
print('video_ids length is '+ str(len(video_ids)))
view_counts = []
# for video_id in video_ids:
# url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={key}&part=statistics'
# r = requests.get(url)
# results = r.json()['items']
# viewCount = results[0]['statistics']['viewCount']
# view_counts.append(int(viewCount))
# print('Number of videos:',len(view_counts))
# print('Average number of views:',sum(view_counts)/len(view_counts))
async def main():
async with aiohttp.ClientSession() as session:
tasks = []
for video_id in video_ids:
task = asyncio.ensure_future(get_video_data(session,video_id))
tasks.append(task)
view_counts = await asyncio.gather(*tasks)
print('Number of videos:',len(view_counts))
print('Average number of views:',sum(view_counts)/len(view_counts))
async def get_video_data(session, video_id):
url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={key}&part=statistics'
async with session.get(url) as response:
result_data = await response.json()
results = result_data['items']
viewCount = results[0]['statistics']['viewCount']
return int(viewCount)
asyncio.run(main())
print("--- %s seconds ---" % (time.time() - start_time))