Last active
August 1, 2025 04:00
-
-
Save salrashid123/cbfac2ab0045faa474fb1b41e25fc341 to your computer and use it in GitHub Desktop.
Adding x-request-reason to python google cloud clients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import google.auth | |
| from google.oauth2 import service_account | |
| from google.cloud import storage | |
| from google.cloud import pubsub_v1 | |
| ## requirements.txt | |
| # google-cloud-storage | |
| # google-cloud-pubsub | |
| # requests | |
| # google-api-python-client | |
| # httplib2 | |
| # google-cloud-compute-v2 | |
| # google-cloud-compute | |
| # https://github.com/salrashid123/request_reason | |
| credentials, project = google.auth.default() | |
| project='core-eso' | |
| ### Storage | |
| client = storage.Client(project=project, extra_headers={'X-Goog-Request-Reason':'bar'}) | |
| for b in client.list_buckets(): | |
| print(b.name) | |
| ### Compute | |
| from google.cloud import compute_v1 | |
| client = compute_v1.InstancesClient() | |
| request = compute_v1.ListInstancesRequest( | |
| project="core-eso", | |
| zone="us-central1-a" | |
| ) | |
| page_result = client.list(request=request, metadata=[('x-goog-request-reason','bar')]) | |
| for response in page_result: | |
| print(response) | |
| ### OrgPolicy | |
| from google.cloud import orgpolicy_v2 | |
| client = orgpolicy_v2.OrgPolicyClient() | |
| request = orgpolicy_v2.ListConstraintsRequest(parent='projects/995081019036') | |
| response = client.list_constraints(request=request, metadata=[('x-goog-request-reason','bar')]) | |
| for constraint in response.constraints: | |
| print(f"Constraint Name: {constraint.name}") | |
| ### Pubsub | |
| publisher = pubsub_v1.PublisherClient() | |
| project_path = f"projects/{project}" | |
| for topic in publisher.list_topics(request={"project": project_path}, metadata=[('x-goog-request-reason','bar')]): | |
| print(topic) | |
| ### logging | |
| from google.cloud.logging_v2.services import logging_service_v2 | |
| client = logging_service_v2.LoggingServiceV2Client() | |
| project_path = client.common_project_path('core-eso') | |
| entries = client.list_log_entries( | |
| resource_names=[project_path], | |
| filter='severity >= WARNING AND resource.type = "cloud_run_revision"', | |
| order_by="timestamp desc", | |
| metadata=[('x-goog-request-reason','bar')] | |
| ) | |
| for entry in entries: | |
| print(f"Timestamp: {entry.timestamp}, Severity: {entry.severity}, Text Payload: {entry.proto_payload}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
