Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 9c41465

Browse filesBrowse files
feat(dlp): Split template samples into multiple files such that each region tag gets its own file (GoogleCloudPlatform#10783)
* restructured templates files * Corrected import orders
1 parent d32c0db commit 9c41465
Copy full SHA for 9c41465

File tree

Expand file treeCollapse file tree

5 files changed

+299
-263
lines changed
Filter options
Expand file treeCollapse file tree

5 files changed

+299
-263
lines changed
+152Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# Copyright 2023 Google LLC
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+
"""Sample app that sets up Data Loss Prevention API inspect templates."""
16+
17+
import argparse
18+
19+
20+
# [START dlp_create_inspect_template]
21+
from typing import List
22+
from typing import Optional
23+
24+
import google.cloud.dlp
25+
26+
27+
def create_inspect_template(
28+
project: str,
29+
info_types: List[str],
30+
template_id: Optional[str] = None,
31+
display_name: Optional[str] = None,
32+
min_likelihood: Optional[int] = None,
33+
max_findings: Optional[int] = None,
34+
include_quote: Optional[bool] = None,
35+
) -> None:
36+
"""Creates a Data Loss Prevention API inspect template.
37+
Args:
38+
project: The Google Cloud project id to use as a parent resource.
39+
info_types: A list of strings representing info types to look for.
40+
A full list of info type categories can be fetched from the API.
41+
template_id: The id of the template. If omitted, an id will be randomly
42+
generated.
43+
display_name: The optional display name of the template.
44+
min_likelihood: A string representing the minimum likelihood threshold
45+
that constitutes a match. One of: 'LIKELIHOOD_UNSPECIFIED',
46+
'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY'.
47+
max_findings: The maximum number of findings to report; 0 = no maximum.
48+
include_quote: Boolean for whether to display a quote of the detected
49+
information in the results.
50+
Returns:
51+
None; the response from the API is printed to the terminal.
52+
"""
53+
54+
# Instantiate a client.
55+
dlp = google.cloud.dlp_v2.DlpServiceClient()
56+
57+
# Prepare info_types by converting the list of strings into a list of
58+
# dictionaries (protos are also accepted).
59+
info_types = [{"name": info_type} for info_type in info_types]
60+
61+
# Construct the configuration dictionary. Keys which are None may
62+
# optionally be omitted entirely.
63+
inspect_config = {
64+
"info_types": info_types,
65+
"min_likelihood": min_likelihood,
66+
"include_quote": include_quote,
67+
"limits": {"max_findings_per_request": max_findings},
68+
}
69+
70+
inspect_template = {
71+
"inspect_config": inspect_config,
72+
"display_name": display_name,
73+
}
74+
75+
# Convert the project id into a full resource id.
76+
parent = f"projects/{project}"
77+
78+
# Call the API.
79+
response = dlp.create_inspect_template(
80+
request={
81+
"parent": parent,
82+
"inspect_template": inspect_template,
83+
"template_id": template_id,
84+
}
85+
)
86+
87+
print(f"Successfully created template {response.name}")
88+
89+
90+
# [END dlp_create_inspect_template]
91+
92+
93+
if __name__ == "__main__":
94+
parser = argparse.ArgumentParser()
95+
96+
parser.add_argument(
97+
"--template_id",
98+
help="The id of the template. If omitted, an id will be randomly " "generated",
99+
)
100+
parser.add_argument(
101+
"--display_name", help="The optional display name of the template."
102+
)
103+
parser.add_argument(
104+
"--project",
105+
help="The Google Cloud project id to use as a parent resource.",
106+
)
107+
parser.add_argument(
108+
"--info_types",
109+
nargs="+",
110+
help="Strings representing info types to look for. A full list of "
111+
"info categories and types is available from the API. Examples "
112+
'include "FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS". '
113+
"If unspecified, the three above examples will be used.",
114+
default=["FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS"],
115+
)
116+
parser.add_argument(
117+
"--min_likelihood",
118+
choices=[
119+
"LIKELIHOOD_UNSPECIFIED",
120+
"VERY_UNLIKELY",
121+
"UNLIKELY",
122+
"POSSIBLE",
123+
"LIKELY",
124+
"VERY_LIKELY",
125+
],
126+
help="A string representing the minimum likelihood threshold that "
127+
"constitutes a match.",
128+
)
129+
parser.add_argument(
130+
"--max_findings",
131+
type=int,
132+
help="The maximum number of findings to report; 0 = no maximum.",
133+
)
134+
parser.add_argument(
135+
"--include_quote",
136+
type=bool,
137+
help="A boolean for whether to display a quote of the detected "
138+
"information in the results.",
139+
default=True,
140+
)
141+
142+
args = parser.parse_args()
143+
144+
create_inspect_template(
145+
args.project,
146+
args.info_types,
147+
template_id=args.template_id,
148+
display_name=args.display_name,
149+
min_likelihood=args.min_likelihood,
150+
max_findings=args.max_findings,
151+
include_quote=args.include_quote,
152+
)
+62Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Copyright 2023 Google LLC
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+
"""Sample app that sets up Data Loss Prevention API inspect templates."""
16+
17+
import argparse
18+
19+
20+
# [START dlp_delete_inspect_template]
21+
import google.cloud.dlp
22+
23+
24+
def delete_inspect_template(project: str, template_id: str) -> None:
25+
"""Deletes a Data Loss Prevention API template.
26+
Args:
27+
project: The id of the Google Cloud project which owns the template.
28+
template_id: The id of the template to delete.
29+
Returns:
30+
None; the response from the API is printed to the terminal.
31+
"""
32+
33+
# Instantiate a client.
34+
dlp = google.cloud.dlp_v2.DlpServiceClient()
35+
36+
# Convert the project id into a full resource id.
37+
parent = f"projects/{project}"
38+
39+
# Combine the template id with the parent id.
40+
template_resource = f"{parent}/inspectTemplates/{template_id}"
41+
42+
# Call the API.
43+
dlp.delete_inspect_template(request={"name": template_resource})
44+
45+
print(f"Template {template_resource} successfully deleted.")
46+
47+
48+
# [END dlp_delete_inspect_template]
49+
50+
51+
if __name__ == "__main__":
52+
53+
parser = argparse.ArgumentParser(description=__doc__)
54+
55+
parser.add_argument("template_id", help="The id of the template to delete.")
56+
parser.add_argument(
57+
"--project",
58+
help="The Google Cloud project id to use as a parent resource.",
59+
)
60+
61+
args = parser.parse_args()
62+
delete_inspect_template(args.project, args.template_id)
+74Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Copyright 2023 Google LLC
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+
"""Sample app that sets up Data Loss Prevention API inspect templates."""
16+
17+
import argparse
18+
19+
20+
# [START dlp_list_inspect_templates]
21+
import google.cloud.dlp
22+
23+
24+
def list_inspect_templates(project: str) -> None:
25+
"""Lists all Data Loss Prevention API inspect templates.
26+
Args:
27+
project: The Google Cloud project id to use as a parent resource.
28+
Returns:
29+
None; the response from the API is printed to the terminal.
30+
"""
31+
32+
# Instantiate a client.
33+
dlp = google.cloud.dlp_v2.DlpServiceClient()
34+
35+
# Convert the project id into a full resource id.
36+
parent = f"projects/{project}"
37+
38+
# Call the API.
39+
response = dlp.list_inspect_templates(request={"parent": parent})
40+
41+
for template in response:
42+
print(f"Template {template.name}:")
43+
if template.display_name:
44+
print(f" Display Name: {template.display_name}")
45+
print(f" Created: {template.create_time}")
46+
print(f" Updated: {template.update_time}")
47+
48+
config = template.inspect_config
49+
print(
50+
" InfoTypes: {}".format(", ".join([it.name for it in config.info_types]))
51+
)
52+
print(f" Minimum likelihood: {config.min_likelihood}")
53+
print(f" Include quotes: {config.include_quote}")
54+
print(
55+
" Max findings per request: {}".format(
56+
config.limits.max_findings_per_request
57+
)
58+
)
59+
60+
61+
# [END dlp_list_inspect_templates]
62+
63+
64+
if __name__ == "__main__":
65+
66+
parser = argparse.ArgumentParser(description=__doc__)
67+
68+
parser.add_argument(
69+
"--project",
70+
help="The Google Cloud project id to use as a parent resource.",
71+
)
72+
73+
args = parser.parse_args()
74+
list_inspect_templates(args.project)

‎dlp/snippets/templates_test.py renamed to ‎dlp/snippets/Templates/templates_test.py

Copy file name to clipboardExpand all lines: dlp/snippets/Templates/templates_test.py
+11-7Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,15 @@
1515
import os
1616
import uuid
1717

18+
import create_inspect_template as ct
19+
import delete_inspect_template as dt
20+
1821
import google.api_core.exceptions
1922
import google.cloud.storage
20-
import pytest
2123

22-
import templates
24+
import list_inspect_templates as lt
25+
26+
import pytest
2327

2428

2529
UNIQUE_STRING = str(uuid.uuid4()).split("-")[0]
@@ -29,20 +33,20 @@
2933

3034
def test_create_list_and_delete_template(capsys: pytest.CaptureFixture) -> None:
3135
try:
32-
templates.create_inspect_template(
36+
ct.create_inspect_template(
3337
GCLOUD_PROJECT,
3438
["FIRST_NAME", "EMAIL_ADDRESS", "PHONE_NUMBER"],
3539
template_id=TEST_TEMPLATE_ID,
3640
)
3741
except google.api_core.exceptions.InvalidArgument:
3842
# Template already exists, perhaps due to a previous interrupted test.
39-
templates.delete_inspect_template(GCLOUD_PROJECT, TEST_TEMPLATE_ID)
43+
dt.delete_inspect_template(GCLOUD_PROJECT, TEST_TEMPLATE_ID)
4044

4145
out, _ = capsys.readouterr()
4246
assert TEST_TEMPLATE_ID in out
4347

4448
# Try again and move on.
45-
templates.create_inspect_template(
49+
ct.create_inspect_template(
4650
GCLOUD_PROJECT,
4751
["FIRST_NAME", "EMAIL_ADDRESS", "PHONE_NUMBER"],
4852
template_id=TEST_TEMPLATE_ID,
@@ -51,12 +55,12 @@ def test_create_list_and_delete_template(capsys: pytest.CaptureFixture) -> None:
5155
out, _ = capsys.readouterr()
5256
assert TEST_TEMPLATE_ID in out
5357

54-
templates.list_inspect_templates(GCLOUD_PROJECT)
58+
lt.list_inspect_templates(GCLOUD_PROJECT)
5559

5660
out, _ = capsys.readouterr()
5761
assert TEST_TEMPLATE_ID in out
5862

59-
templates.delete_inspect_template(GCLOUD_PROJECT, TEST_TEMPLATE_ID)
63+
dt.delete_inspect_template(GCLOUD_PROJECT, TEST_TEMPLATE_ID)
6064

6165
out, _ = capsys.readouterr()
6266
assert TEST_TEMPLATE_ID in out

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.