Skip to content

Commit 8d65212

Browse files
"Added sample: python/retrieve_reports.py"
1 parent cf5fbdd commit 8d65212

1 file changed

Lines changed: 143 additions & 0 deletions

File tree

python/retrieve_reports.py

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
#!/usr/bin/python
2+
3+
# Usage example:
4+
# python retrieve_reports.py
5+
6+
import httplib2
7+
import os
8+
import sys
9+
10+
from apiclient.discovery import build
11+
from apiclient.errors import HttpError
12+
from apiclient.http import MediaIoBaseDownload
13+
from io import FileIO
14+
from oauth2client.client import flow_from_clientsecrets
15+
from oauth2client.file import Storage
16+
from oauth2client.tools import argparser, run_flow
17+
18+
19+
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
20+
21+
# the OAuth 2.0 information for this application, including its client_id and
22+
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
23+
# the {{ Google Cloud Console }} at
24+
# {{ https://cloud.google.com/console }}.
25+
# Please ensure that you have enabled the YouTube Data API for your project.
26+
# For more information about using OAuth2 to access the YouTube Data API, see:
27+
# https://developers.google.com/youtube/v3/guides/authentication
28+
# For more information about the client_secrets.json file format, see:
29+
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
30+
CLIENT_SECRETS_FILE = "client_secrets.json"
31+
32+
# This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
33+
# authenticated user's account. Any request that retrieves earnings or ad performance metrics must
34+
# use this scope.
35+
YOUTUBE_ANALYTICS_MONETARY_READ_SCOPE = (
36+
"https://www.googleapis.com/auth/yt-analytics-monetary.readonly")
37+
YOUTUBE_REPORTING_API_SERVICE_NAME = "youtubereporting"
38+
YOUTUBE_REPORTING_API_VERSION = "v1"
39+
40+
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
41+
# missing.
42+
MISSING_CLIENT_SECRETS_MESSAGE = """
43+
WARNING: Please configure OAuth 2.0
44+
45+
To make this sample run you will need to populate the client_secrets.json file
46+
found at:
47+
%s
48+
with information from the APIs Console
49+
https://console.developers.google.com
50+
51+
For more information about the client_secrets.json file format, please visit:
52+
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
53+
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
54+
CLIENT_SECRETS_FILE))
55+
56+
# Authorize the request and store authorization credentials.
57+
def get_authenticated_service(args):
58+
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_ANALYTICS_MONETARY_READ_SCOPE,
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+
return build(YOUTUBE_REPORTING_API_SERVICE_NAME, YOUTUBE_REPORTING_API_VERSION,
68+
http=credentials.authorize(httplib2.Http()))
69+
70+
71+
# Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
72+
def list_reporting_jobs(youtube_reporting):
73+
results = youtube_reporting.jobs().list(
74+
).execute()
75+
76+
if "jobs" in results and results["jobs"]:
77+
jobs = results["jobs"]
78+
for job in jobs:
79+
print ("Reporting job id: %s\n name: %s\n for reporting type: %s\n"
80+
% (job["id"], job["name"], job["reportTypeId"]))
81+
else:
82+
print "No jobs found"
83+
return False
84+
85+
return True
86+
87+
88+
# Call the YouTube Reporting API's reports.list method to retrieve reports created by a job.
89+
def retrieve_reports(youtube_reporting, job_id):
90+
results = youtube_reporting.jobs().reports().list(
91+
jobId=job_id
92+
).execute()
93+
94+
if "reports" in results and results["reports"]:
95+
reports = results["reports"]
96+
for report in reports:
97+
print ("Report from '%s' to '%s' downloadable at '%s'"
98+
% (report["startTime"], report["endTime"], report["downloadUrl"]))
99+
100+
101+
# Call the YouTube Reporting API's media.download method to download the report.
102+
def download_report(youtube_reporting, report_url):
103+
request = youtube_reporting.media().download(
104+
resourceName=""
105+
)
106+
request.uri = report_url
107+
fh = FileIO('report', mode='wb')
108+
# Stream/download the report in a single request.
109+
downloader = MediaIoBaseDownload(fh, request, chunksize=-1)
110+
111+
done = False
112+
while done is False:
113+
status, done = downloader.next_chunk()
114+
if status:
115+
print "Download %d%%." % int(status.progress() * 100)
116+
print "Download Complete!"
117+
118+
119+
# Prompt the user to enter a job id for report retrieval. Then return the id.
120+
def get_job_id_from_user():
121+
job_id = raw_input("Please enter the job id for the report retrieval: ")
122+
print ("You chose '%s' as the job Id for the report retrieval." % job_id)
123+
return job_id
124+
125+
126+
# Prompt the user to enter a report URL for download. Then return the URL.
127+
def get_report_url_from_user():
128+
report_url = raw_input("Please enter the report URL to download: ")
129+
print ("You chose '%s' to download." % report_url)
130+
return report_url
131+
132+
if __name__ == "__main__":
133+
args = argparser.parse_args()
134+
135+
youtube_reporting = get_authenticated_service(args)
136+
try:
137+
if list_reporting_jobs(youtube_reporting):
138+
retrieve_reports(youtube_reporting, get_job_id_from_user())
139+
download_report(youtube_reporting, get_report_url_from_user())
140+
except HttpError, e:
141+
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
142+
else:
143+
print "Retrieved reports."

0 commit comments

Comments
 (0)