Skip to content

Commit 39d2fc5

Browse files
"Added sample: python/yt_analytics_report.py"
1 parent c9d8e40 commit 39d2fc5

1 file changed

Lines changed: 131 additions & 0 deletions

File tree

python/yt_analytics_report.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
#!/usr/bin/python
2+
3+
from datetime import datetime, timedelta
4+
import httplib2
5+
import os
6+
import sys
7+
8+
from apiclient.discovery import build
9+
from apiclient.errors import HttpError
10+
from oauth2client.client import flow_from_clientsecrets
11+
from oauth2client.file import Storage
12+
from oauth2client.tools import argparser, run_flow
13+
14+
15+
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
16+
# the OAuth 2.0 information for this application, including its client_id and
17+
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
18+
# the {{ Google Cloud Console }} at
19+
# {{ https://cloud.google.com/console }}.
20+
# Please ensure that you have enabled the YouTube Data and YouTube Analytics
21+
# APIs for your project.
22+
# For more information about using OAuth2 to access the YouTube Data API, see:
23+
# https://developers.google.com/youtube/v3/guides/authentication
24+
# For more information about the client_secrets.json file format, see:
25+
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
26+
CLIENT_SECRETS_FILE = "client_secrets.json"
27+
28+
# These OAuth 2.0 access scopes allow for read-only access to the authenticated
29+
# user's account for both YouTube Data API resources and YouTube Analytics Data.
30+
YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly",
31+
"https://www.googleapis.com/auth/yt-analytics.readonly"]
32+
YOUTUBE_API_SERVICE_NAME = "youtube"
33+
YOUTUBE_API_VERSION = "v3"
34+
YOUTUBE_ANALYTICS_API_SERVICE_NAME = "youtubeAnalytics"
35+
YOUTUBE_ANALYTICS_API_VERSION = "v1"
36+
37+
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
38+
# missing.
39+
MISSING_CLIENT_SECRETS_MESSAGE = """
40+
WARNING: Please configure OAuth 2.0
41+
42+
To make this sample run you will need to populate the client_secrets.json file
43+
found at:
44+
45+
%s
46+
47+
with information from the {{ Cloud Console }}
48+
{{ https://cloud.google.com/console }}
49+
50+
For more information about the client_secrets.json file format, please visit:
51+
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
52+
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
53+
CLIENT_SECRETS_FILE))
54+
55+
56+
def get_authenticated_services(args):
57+
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
58+
scope=" ".join(YOUTUBE_SCOPES),
59+
message=MISSING_CLIENT_SECRETS_MESSAGE)
60+
61+
storage = Storage("%s-oauth2.json" % sys.argv[0])
62+
credentials = storage.get()
63+
64+
if credentials is None or credentials.invalid:
65+
credentials = run_flow(flow, storage, args)
66+
67+
http = credentials.authorize(httplib2.Http())
68+
69+
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
70+
http=http)
71+
youtube_analytics = build(YOUTUBE_ANALYTICS_API_SERVICE_NAME,
72+
YOUTUBE_ANALYTICS_API_VERSION, http=http)
73+
74+
return (youtube, youtube_analytics)
75+
76+
def get_channel_id(youtube):
77+
channels_list_response = youtube.channels().list(
78+
mine=True,
79+
part="id"
80+
).execute()
81+
82+
return channels_list_response["items"][0]["id"]
83+
84+
def run_analytics_report(youtube_analytics, channel_id, options):
85+
# Call the Analytics API to retrieve a report. For a list of available
86+
# reports, see:
87+
# https://developers.google.com/youtube/analytics/v1/channel_reports
88+
analytics_query_response = youtube_analytics.reports().query(
89+
ids="channel==%s" % channel_id,
90+
metrics=options.metrics,
91+
dimensions=options.dimensions,
92+
start_date=options.start_date,
93+
end_date=options.end_date,
94+
max_results=options.max_results,
95+
sort=options.sort
96+
).execute()
97+
98+
print "Analytics Data for Channel %s" % channel_id
99+
100+
for column_header in analytics_query_response.get("columnHeaders", []):
101+
print "%-20s" % column_header["name"],
102+
print
103+
104+
for row in analytics_query_response.get("rows", []):
105+
for value in row:
106+
print "%-20s" % value,
107+
print
108+
109+
if __name__ == "__main__":
110+
now = datetime.now()
111+
one_day_ago = (now - timedelta(days=1)).strftime("%Y-%m-%d")
112+
one_week_ago = (now - timedelta(days=7)).strftime("%Y-%m-%d")
113+
114+
argparser.add_argument("--metrics", help="Report metrics",
115+
default="views,comments,favoritesAdded,favoritesRemoved,likes,dislikes,shares")
116+
argparser.add_argument("--dimensions", help="Report dimensions",
117+
default="video")
118+
argparser.add_argument("--start-date", default=one_week_ago,
119+
help="Start date, in YYYY-MM-DD format")
120+
argparser.add_argument("--end-date", default=one_day_ago,
121+
help="End date, in YYYY-MM-DD format")
122+
argparser.add_argument("--max-results", help="Max results", default=10)
123+
argparser.add_argument("--sort", help="Sort order", default="-views")
124+
args = argparser.parse_args()
125+
126+
(youtube, youtube_analytics) = get_authenticated_services(args)
127+
try:
128+
channel_id = get_channel_id(youtube)
129+
run_analytics_report(youtube_analytics, channel_id, args)
130+
except HttpError, e:
131+
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

0 commit comments

Comments
 (0)