forked from pinterest/api-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_analytics.py
More file actions
executable file
·253 lines (224 loc) · 9.14 KB
/
get_analytics.py
File metadata and controls
executable file
·253 lines (224 loc) · 9.14 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#!/usr/bin/env python
import argparse
import json
import sys
from os.path import abspath, dirname, join
sys.path.append(abspath(join(dirname(__file__), "..", "src")))
from api_config import ApiConfig
from arguments import common_arguments
from utils import input_number, input_path_for_write
def find_and_get_analytics(
advertisers, analytics_object, ads_entities, get_args, level
):
"""
Recursive function that prints out one level of advertising entity
and then calls itself to print entities at lower levels.
"""
entity = ads_entities[level]
kind = entity["kind"]
if entity["identifier"]:
entity_id = entity["identifier"]
print(f"Using the {kind} with identifier: {entity_id}")
else:
entity_list = list(entity["get"](*get_args))
n_entities = len(entity_list)
if not n_entities:
print(f"This {entity['parent']} has no {kind}s.")
return None
advertisers.print_enumeration(entity_list, kind)
# Prompt to get the entity index.
prompt = f"Please select the {kind} number between 1 and {n_entities}:"
index = input_number(prompt, 1, n_entities)
entity_id = entity_list[index - 1]["id"]
get_args += [entity_id]
if entity["object"] == analytics_object:
return entity["analytics"](*get_args)
level += 1
if level == len(ads_entities):
return None
return find_and_get_analytics(
advertisers, analytics_object, ads_entities, get_args, level
)
def main(argv=[]):
"""
This script shows how to use the Pinterest API synchronous analytics endpoints
to download reports for a User, Ad Account, Campaign, Ad Group, or Ad. The
analytics_api_example script shows how to use Pinterest API v3 to retrieve
similar metrics using asynchronous reporting functionality.
This script fetches user analytics by default, which just requires an
access token with READ_USERS scope.
Using this script for advertising analytics requires a login or an access token
for a Pinterest user account that has linked Ad Accounts. (The relationship
between User and Ad Accounts is 1-to-many.) To get a report with useful
metrics values, at least one linked Ad Account needs to have an active
advertising campaign. The access token requires READ_USERS and
READ_ADVERTISERS scopes.
"""
parser = argparse.ArgumentParser(description="Get Analytics")
parser.add_argument(
"-o",
"--analytics-object",
default="user",
choices=[
"user",
"pin",
"ad_account_user",
"ad_account",
"campaign",
"ad_group",
"ad",
],
help="kind of object used to fetch analytics",
)
parser.add_argument("--pin-id", help="Get analytics for this pin identifier.")
parser.add_argument(
"--ad-account-id", help="Get analytics for this ad account identifier."
)
parser.add_argument(
"--campaign-id", help="Get analytics for this campaign identifier."
)
parser.add_argument(
"--ad-group-id", help="Get analytics for this ad group identifier."
)
parser.add_argument("--ad-id", help="Get analytics for this ad identifier.")
common_arguments(parser)
args = parser.parse_args(argv)
# Specifying identifier at one level requires specifying identifier at levels above.
if args.campaign_id and not args.ad_account_id:
print("Ad account identifier must be specified when using campaign identifier")
exit(1)
if args.ad_group_id and not args.campaign_id:
print("Campaign identifier must be specified when using ad group identifier")
exit(1)
if args.ad_id and not args.ad_ad_group_id:
print("Ad group identifier must be specified when using ad identifier")
exit(1)
api_config = ApiConfig(verbosity=args.log_level, version=args.api_version)
# This API edge case is best handled up right after API set-up...
if api_config.version < "v5" and args.analytics_object == "pin":
print("Pin analytics for shared accounts are")
print("supported by Pinterest API v5, but not v3 or v4.")
print("Try using -v5 or an analytics object besides pin.")
exit(1)
if api_config.version < "v5" and args.analytics_object == "ad_account_user":
print("User account analytics for shared accounts are")
print("supported by Pinterest API v5, but not v3 or v4.")
print("Try using -v5 or an analytics object besides ad_account_user.")
exit(1)
# Requesting pin analytics requires a pin_id.
if args.analytics_object == "pin" and not args.pin_id:
print("Pin analytics require a pin identifier.")
exit(1)
# imports that depend on the version of the API
from access_token import AccessToken
from advertisers import Advertisers
from analytics import AdAnalytics, PinAnalytics, UserAnalytics
from oauth_scope import Scope
from user import User
"""
Fetch an access token and print summary data about the User.
"""
access_token = AccessToken(api_config, name=args.access_token)
scopes = [Scope.READ_USERS]
if args.analytics_object != "user":
scopes += [Scope.READ_ADVERTISERS]
access_token.fetch(scopes=scopes)
# Get the user record. Some versions of the Pinterest API require the
# user id associated with the access token.
user_me = User("me", api_config, access_token)
user_me_data = user_me.get()
user_me.print_summary(user_me_data)
if args.analytics_object == "user":
# Get analytics for the user account associated with the access token.
analytics = (
UserAnalytics(user_me_data.get("id"), api_config, access_token)
.last_30_days()
.metrics({"IMPRESSION", "PIN_CLICK_RATE"})
)
results = analytics.get() # not calling with an ad_account_id argument
elif args.analytics_object == "pin":
# Get analytics for the pin.
analytics = (
PinAnalytics(args.pin_id, api_config, access_token)
.last_30_days()
.metrics({"IMPRESSION", "PIN_CLICK"})
)
results = analytics.get(args.ad_account_id) # ad account id may be None
elif args.analytics_object == "ad_account_user":
# Get analytics for the user account associated with an ad account.
analytics = (
UserAnalytics(user_me_data.get("id"), api_config, access_token)
.last_30_days()
.metrics({"IMPRESSION", "PIN_CLICK_RATE"})
)
advertisers = Advertisers(user_me_data.get("id"), api_config, access_token)
# When using find_and_get_analytics, analytics.get() will be called with
# an ad_account_id argument.
ads_entities = [
{
"object": "ad_account",
"kind": "Ad Account",
"parent": "User",
"get": advertisers.get,
"analytics": analytics.get,
"identifier": args.ad_account_id,
}
]
results = find_and_get_analytics(advertisers, "ad_account", ads_entities, [], 0)
else:
# Get advertising analytics for the appropriate kind of object.
analytics = (
AdAnalytics(api_config, access_token)
.last_30_days()
.metrics({"SPEND_IN_DOLLAR", "TOTAL_CLICKTHROUGH"})
.granularity("DAY")
)
advertisers = Advertisers(user_me_data.get("id"), api_config, access_token)
ads_entities = [
{
"object": "ad_account",
"kind": "Ad Account",
"parent": "User",
"get": advertisers.get,
"analytics": analytics.get_ad_account,
"identifier": args.ad_account_id,
},
{
"object": "campaign",
"kind": "Campaign",
"parent": "Ad Account",
"get": advertisers.get_campaigns,
"analytics": analytics.get_campaign,
"identifier": args.campaign_id,
},
{
"object": "ad_group",
"kind": "Ad Group",
"parent": "Campaign",
"get": advertisers.get_ad_groups,
"analytics": analytics.get_ad_group,
"identifier": args.ad_group_id,
},
{
"object": "ad",
"kind": "Ad",
"parent": "Ad Group",
"get": advertisers.get_ads,
"analytics": analytics.get_ad,
"identifier": args.ad_id,
},
]
results = find_and_get_analytics(
advertisers, args.analytics_object, ads_entities, [], 0
)
if not results:
print("There are no analytics results.")
return
# Prompt for the name of an output file and write the analytics results.
path = input_path_for_write(
"Please enter a file name for the analytics output:", "analytics_output.json"
)
with open(path, "w") as json_file:
json.dump(results, json_file, indent=2)
if __name__ == "__main__":
main(sys.argv[1:])