Skip to content

Commit 660971d

Browse files
ikuleshovpartheagcf-owl-bot[bot]
authored
docs: add a sample for runAccessReport method (#289)
* update test configuration * remove custom noxfile configs for now * remove MaximumUserAccess rom sample * add comment in noxfile_config.py * run blacken session * lint * add pytest * Update noxfile_config.py * Update noxfile_config.py * delete enhanced measurement settings samples as this functionality is no longer supported in v1alpha * fix the samples tests * do not use the `maximum_user_access` field and `update` operation in properties.firebase_links tests as this is no longer supported in v1alpha * use `creator_email_address` instead of `email_address` field in properties.google_ads_links_list() test as the field has been renamed in v1alpha * fix the samples test * add a sample for runAccessReport method * add a sample for runAccessReport method * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix the test * fix the test Co-authored-by: Anthonios Partheniou <[email protected]> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 9424fdb commit 660971d

File tree

2 files changed

+140
-0
lines changed

2 files changed

+140
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2022 Google LLC All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Google Analytics Admin API sample application which runs an access report
18+
on a property.
19+
20+
See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/runAccessReport
21+
for more information.
22+
"""
23+
# [START analyticsadmin_properties_run_access_report]
24+
from datetime import datetime
25+
26+
from google.analytics.admin import AnalyticsAdminServiceClient
27+
from google.analytics.admin_v1alpha.types import (
28+
AccessDateRange,
29+
AccessDimension,
30+
AccessMetric,
31+
RunAccessReportRequest,
32+
)
33+
34+
35+
def run_sample():
36+
"""Runs the sample."""
37+
# TODO(developer): Replace this variable with your Google Analytics 4
38+
# property ID (e.g. "123456") before running the sample.
39+
property_id = "YOUR-GA4-PROPERTY-ID"
40+
run_access_report(property_id)
41+
42+
43+
def run_access_report(property_id: str, transport: str = None):
44+
"""
45+
Runs an access report for a Google Analytics property.
46+
Args:
47+
property_id(str): The Google Analytics Property ID.
48+
transport(str): The transport to use. For example, "grpc"
49+
or "rest". If set to None, a transport is chosen automatically.
50+
"""
51+
client = AnalyticsAdminServiceClient(transport=transport)
52+
request = RunAccessReportRequest(
53+
entity=f"properties/{property_id}",
54+
dimensions=[
55+
AccessDimension(dimension_name="userEmail"),
56+
AccessDimension(dimension_name="accessedPropertyId"),
57+
AccessDimension(dimension_name="propertyUserLink"),
58+
AccessDimension(dimension_name="reportType"),
59+
AccessDimension(dimension_name="revenueDataReturned"),
60+
AccessDimension(dimension_name="costDataReturned"),
61+
AccessDimension(dimension_name="userIP"),
62+
AccessDimension(dimension_name="epochTimeMicros"),
63+
AccessDimension(dimension_name="mostRecentAccessEpochTimeMicros"),
64+
],
65+
metrics=[AccessMetric(metric_name="accessCount")],
66+
date_ranges=[AccessDateRange(start_date="yesterday", end_date="today")],
67+
)
68+
69+
access_report = client.run_access_report(request)
70+
71+
print("Result:")
72+
print_access_report(access_report)
73+
74+
75+
def print_access_report(response):
76+
"""Prints the access report."""
77+
print(f"{response.row_count} rows received")
78+
for dimensionHeader in response.dimension_headers:
79+
print(f"Dimension header name: {dimensionHeader.dimension_name}")
80+
for metricHeader in response.metric_headers:
81+
print(f"Metric header name: {metricHeader.metric_name})")
82+
83+
for rowIdx, row in enumerate(response.rows):
84+
print(f"\nRow {rowIdx}")
85+
for i, dimension_value in enumerate(row.dimension_values):
86+
dimension_name = response.dimension_headers[i].dimension_name
87+
if dimension_name.endswith("Micros"):
88+
# Convert microseconds since Unix Epoch to datetime object.
89+
dimension_value_formatted = datetime.utcfromtimestamp(
90+
int(dimension_value.value) / 1000000
91+
)
92+
else:
93+
dimension_value_formatted = dimension_value.value
94+
print(f"{dimension_name}: {dimension_value_formatted}")
95+
96+
for i, metric_value in enumerate(row.metric_values):
97+
metric_name = response.metric_headers[i].metric_name
98+
print(f"{metric_name}: {metric_value.value}")
99+
100+
101+
# [END analyticsadmin_properties_run_access_report]
102+
103+
104+
if __name__ == "__main__":
105+
run_sample()
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Copyright 2022 Google LLC All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
import pytest
18+
19+
import properties_run_access_report
20+
21+
TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")
22+
23+
24+
def test_properties_run_access_report(capsys):
25+
transports = ["grpc", "rest"]
26+
for transport in transports:
27+
# This test ensures that the call is valid and reaches the server, even
28+
# though the operation does not succeed due to permission error.
29+
with pytest.raises(
30+
Exception,
31+
match="Access record reports are only allowed on Google Analytics 360 properties.",
32+
):
33+
properties_run_access_report.run_access_report(
34+
TEST_PROPERTY_ID, transport=transport
35+
)

0 commit comments

Comments
 (0)