Advertisement
J2897

[YouTube API] Average Views (asyncio)

Feb 18th, 2022
1,007
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import aiohttp
  2. import asyncio
  3. import requests
  4. import time
  5. from config import api_key, channel_id, base_url
  6.  
  7. start_time = time.time()
  8.  
  9. # Get the ID from the Uploads Playlist.
  10. url = f'{base_url}/channels?id={channel_id}&key={api_key}&part=contentDetails'
  11. r = requests.get(url)
  12. results = r.json()['items']
  13. playlist_id = results[0]['contentDetails']['relatedPlaylists']['uploads']
  14.  
  15. # Get all of the video IDs.
  16. video_ids = []
  17. url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails'
  18. while True:
  19.     r = requests.get(url)
  20.     results = r.json()
  21.     if 'nextPageToken' in results:
  22.         nextPageToken = results['nextPageToken']
  23.     else:
  24.         nextPageToken = None
  25.  
  26.     if 'items' in results:
  27.         for item in results['items']:
  28.             if 'contentDetails' in item:
  29.                 if 'videoId' in item['contentDetails']:
  30.                     videoId = item['contentDetails']['videoId']
  31.                     video_ids.append(videoId)
  32.  
  33.     if nextPageToken:
  34.         url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails&pageToken={nextPageToken}'
  35.     else:
  36.         break
  37.  
  38. async def main():
  39.     async with aiohttp.ClientSession() as session:
  40.         tasks = []
  41.         for video_id in video_ids:
  42.             task = asyncio.ensure_future(get_video_data(session, video_id))
  43.             tasks.append(task)
  44.  
  45.         view_counts = await asyncio.gather(*tasks)
  46.  
  47.     print('Number of videos:', 2*'\t', len(view_counts))
  48.     print('Average number of views:', '\t', sum(view_counts) / len(view_counts))
  49.  
  50. async def get_video_data(session, video_id):
  51.     url = f'{base_url}/videos?id={video_id}&key={api_key}&part=statistics'
  52.    
  53.     async with session.get(url) as response:
  54.         result_data = await response.json()
  55.         results = result_data['items']
  56.         viewCount = results[0]['statistics']['viewCount']
  57.         return int(viewCount)
  58.  
  59. asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  60. asyncio.run(main())
  61.  
  62. print("--- %s seconds ---" % (time.time() - start_time))
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement