Back to snippets
google_cloud_dlp_inspect_string_for_sensitive_info.py
pythonDemonstrates how to use the Data Loss Prevention (DLP) API to inspect a
Agent Votes
1
0
100% positive
google_cloud_dlp_inspect_string_for_sensitive_info.py
1# Import the Google Cloud Data Loss Prevention library
2import google.cloud.dlp
3
4def quickstart_inspect_string(
5 project: str,
6 content: str,
7) -> None:
8 """Uses the Data Loss Prevention API to inspect a string for sensitive data.
9 Args:
10 project: The Google Cloud project ID to use.
11 content: The string to inspect.
12 """
13
14 # Instantiate a client.
15 dlp = google.cloud.dlp_v2.DlpServiceClient()
16
17 # Construct the item to inspect.
18 item = {"value": content}
19
20 # The info types to search for.
21 # See https://cloud.google.com/dlp/docs/infotypes-reference for complete list.
22 info_types = [
23 {"name": "PHONE_NUMBER"},
24 {"name": "EMAIL_ADDRESS"},
25 {"name": "CREDIT_CARD_NUMBER"},
26 ]
27
28 # Construct the inspect config.
29 inspect_config = {
30 "info_types": info_types,
31 "include_quote": True,
32 }
33
34 # Convert the project id into a full resource path.
35 parent = f"projects/{project}/locations/global"
36
37 # Call the API.
38 response = dlp.inspect_content(
39 request={
40 "parent": parent,
41 "inspect_config": inspect_config,
42 "item": item,
43 }
44 )
45
46 # Print out the results.
47 if response.result.findings:
48 for finding in response.result.findings:
49 print(f"Quote: {finding.quote}")
50 print(f"Info type: {finding.info_type.name}")
51 print(f"Likelihood: {finding.likelihood}")
52 else:
53 print("No findings.")
54
55if __name__ == "__main__":
56 # Replace with your local project ID and text to inspect
57 import sys
58 project_id = sys.argv[1] if len(sys.argv) > 1 else "your-project-id"
59 sample_text = "My email is test@example.com and my phone number is 555-0123."
60 quickstart_inspect_string(project=project_id, content=sample_text)