0
# Asynchronous Client Operations
1
2
Asynchronous versions of all service management and discovery operations for non-blocking I/O in async applications. The async client provides the same functionality as the synchronous client but with async/await support.
3
4
## Client Initialization
5
6
```python { .api }
7
class ServiceUsageAsyncClient:
8
"""Async client for Google Cloud Service Usage API."""
9
10
def __init__(
11
self,
12
*,
13
credentials: Optional[ga_credentials.Credentials] = None,
14
transport: Optional[Union[str, ServiceUsageTransport]] = None,
15
client_options: Optional[ClientOptions] = None,
16
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO
17
):
18
"""Initialize the async client."""
19
20
async def __aenter__(self) -> "ServiceUsageAsyncClient":
21
"""Async context manager entry."""
22
23
async def __aexit__(self, exc_type, exc, tb):
24
"""Async context manager exit."""
25
```
26
27
Usage example:
28
29
```python
30
import asyncio
31
from google.cloud import service_usage
32
33
async def main():
34
async with service_usage.ServiceUsageAsyncClient() as client:
35
# Use the client for async operations
36
pass
37
38
# Run the async function
39
asyncio.run(main())
40
```
41
42
## Capabilities
43
44
### Async Service Management
45
46
Asynchronous versions of service enable, disable, and batch operations.
47
48
```python { .api }
49
async def enable_service(
50
request: EnableServiceRequest,
51
*,
52
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
53
timeout: Optional[float] = None,
54
metadata: Sequence[Tuple[str, str]] = ()
55
) -> AsyncOperation[EnableServiceResponse, OperationMetadata]:
56
"""
57
Asynchronously enable a service for a project.
58
59
Args:
60
request: The request object containing the service name
61
retry: Async retry configuration
62
timeout: Request timeout in seconds
63
metadata: Additional metadata for the request
64
65
Returns:
66
Async long-running operation that resolves to EnableServiceResponse
67
"""
68
69
async def disable_service(
70
request: DisableServiceRequest,
71
*,
72
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
73
timeout: Optional[float] = None,
74
metadata: Sequence[Tuple[str, str]] = ()
75
) -> AsyncOperation[DisableServiceResponse, OperationMetadata]:
76
"""
77
Asynchronously disable a service for a project.
78
79
Args:
80
request: The request object containing the service name and options
81
retry: Async retry configuration
82
timeout: Request timeout in seconds
83
metadata: Additional metadata for the request
84
85
Returns:
86
Async long-running operation that resolves to DisableServiceResponse
87
"""
88
89
async def batch_enable_services(
90
request: BatchEnableServicesRequest,
91
*,
92
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
93
timeout: Optional[float] = None,
94
metadata: Sequence[Tuple[str, str]] = ()
95
) -> AsyncOperation[BatchEnableServicesResponse, OperationMetadata]:
96
"""
97
Asynchronously enable multiple services in a single operation.
98
99
Args:
100
request: The request object containing parent and service IDs
101
retry: Async retry configuration
102
timeout: Request timeout in seconds
103
metadata: Additional metadata for the request
104
105
Returns:
106
Async long-running operation that resolves to BatchEnableServicesResponse
107
"""
108
```
109
110
Usage example:
111
112
```python
113
import asyncio
114
from google.cloud import service_usage
115
116
async def enable_services_async():
117
async with service_usage.ServiceUsageAsyncClient() as client:
118
# Enable a single service
119
service_name = "projects/my-project-id/services/storage.googleapis.com"
120
request = service_usage.EnableServiceRequest(name=service_name)
121
122
operation = await client.enable_service(request=request)
123
result = await operation.result()
124
print(f"Service enabled: {result.service.name}")
125
126
# Batch enable multiple services
127
parent = "projects/my-project-id"
128
batch_request = service_usage.BatchEnableServicesRequest(
129
parent=parent,
130
service_ids=["compute.googleapis.com", "bigquery.googleapis.com"]
131
)
132
133
batch_operation = await client.batch_enable_services(request=batch_request)
134
batch_result = await batch_operation.result()
135
print(f"Enabled {len(batch_result.services)} services")
136
137
asyncio.run(enable_services_async())
138
```
139
140
### Async Service Discovery
141
142
Asynchronous versions of service query and discovery operations.
143
144
```python { .api }
145
async def get_service(
146
request: GetServiceRequest,
147
*,
148
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
149
timeout: Optional[float] = None,
150
metadata: Sequence[Tuple[str, str]] = ()
151
) -> Service:
152
"""
153
Asynchronously get information about a specific service.
154
155
Args:
156
request: The request object containing the service name
157
retry: Async retry configuration
158
timeout: Request timeout in seconds
159
metadata: Additional metadata for the request
160
161
Returns:
162
Service object with configuration details
163
"""
164
165
async def list_services(
166
request: ListServicesRequest,
167
*,
168
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
169
timeout: Optional[float] = None,
170
metadata: Sequence[Tuple[str, str]] = ()
171
) -> ListServicesAsyncPager:
172
"""
173
Asynchronously list services available to a project.
174
175
Args:
176
request: The request object with parent and filtering options
177
retry: Async retry configuration
178
timeout: Request timeout in seconds
179
metadata: Additional metadata for the request
180
181
Returns:
182
Async paginated iterator over Service objects
183
"""
184
185
async def batch_get_services(
186
request: BatchGetServicesRequest,
187
*,
188
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
189
timeout: Optional[float] = None,
190
metadata: Sequence[Tuple[str, str]] = ()
191
) -> BatchGetServicesResponse:
192
"""
193
Asynchronously get information about multiple services.
194
195
Args:
196
request: The request object containing parent and service names
197
retry: Async retry configuration
198
timeout: Request timeout in seconds
199
metadata: Additional metadata for the request
200
201
Returns:
202
BatchGetServicesResponse with list of services
203
"""
204
```
205
206
Usage example:
207
208
```python
209
import asyncio
210
from google.cloud import service_usage
211
212
async def discover_services_async():
213
async with service_usage.ServiceUsageAsyncClient() as client:
214
# Get a specific service
215
service_name = "projects/my-project-id/services/storage.googleapis.com"
216
request = service_usage.GetServiceRequest(name=service_name)
217
218
service = await client.get_service(request=request)
219
print(f"Service: {service.config.title}")
220
print(f"State: {service.state.name}")
221
222
# List all services asynchronously
223
parent = "projects/my-project-id"
224
list_request = service_usage.ListServicesRequest(parent=parent)
225
226
async for service in await client.list_services(request=list_request):
227
print(f"Service: {service.name} - {service.state.name}")
228
229
# Batch get multiple services
230
service_names = [
231
f"{parent}/services/storage.googleapis.com",
232
f"{parent}/services/compute.googleapis.com"
233
]
234
batch_request = service_usage.BatchGetServicesRequest(
235
parent=parent,
236
names=service_names
237
)
238
239
batch_response = await client.batch_get_services(request=batch_request)
240
for service in batch_response.services:
241
print(f"Batch result: {service.config.title}")
242
243
asyncio.run(discover_services_async())
244
```
245
246
### Async Operations Management
247
248
Asynchronous operations for managing long-running tasks.
249
250
```python { .api }
251
async def list_operations(
252
request: ListOperationsRequest,
253
*,
254
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
255
timeout: Optional[float] = None,
256
metadata: Sequence[Tuple[str, str]] = ()
257
) -> ListOperationsAsyncPager:
258
"""
259
Asynchronously list long-running operations.
260
261
Args:
262
request: The request object for listing operations
263
retry: Async retry configuration
264
timeout: Request timeout in seconds
265
metadata: Additional metadata for the request
266
267
Returns:
268
Async paginated iterator over Operation objects
269
"""
270
271
async def get_operation(
272
request: GetOperationRequest,
273
*,
274
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
275
timeout: Optional[float] = None,
276
metadata: Sequence[Tuple[str, str]] = ()
277
) -> Operation:
278
"""
279
Asynchronously get details of a long-running operation.
280
281
Args:
282
request: The request object containing operation name
283
retry: Async retry configuration
284
timeout: Request timeout in seconds
285
metadata: Additional metadata for the request
286
287
Returns:
288
Operation object with current status and result
289
"""
290
```
291
292
## Async Pager
293
294
```python { .api }
295
class ListServicesAsyncPager:
296
"""Async pager for iterating through list_services results."""
297
298
def __aiter__(self) -> AsyncIterator[Service]:
299
"""Asynchronously iterate through Service objects."""
300
301
@property
302
def pages(self) -> AsyncIterator[ListServicesResponse]:
303
"""Asynchronously iterate through response pages."""
304
```
305
306
Usage example:
307
308
```python
309
import asyncio
310
from google.cloud import service_usage
311
312
async def paginate_services_async():
313
async with service_usage.ServiceUsageAsyncClient() as client:
314
parent = "projects/my-project-id"
315
request = service_usage.ListServicesRequest(
316
parent=parent,
317
page_size=5
318
)
319
320
pager = await client.list_services(request=request)
321
322
# Iterate through individual services
323
async for service in pager:
324
print(f"Service: {service.name}")
325
326
# Or iterate through pages
327
async for page in pager.pages:
328
print(f"Page with {len(page.services)} services")
329
for service in page.services:
330
print(f" {service.config.title}")
331
332
asyncio.run(paginate_services_async())
333
```
334
335
## Async Context Manager Pattern
336
337
```python
338
import asyncio
339
from google.cloud import service_usage
340
341
async def async_context_example():
342
# Using async context manager for automatic cleanup
343
async with service_usage.ServiceUsageAsyncClient() as client:
344
# All async operations here
345
parent = "projects/my-project-id"
346
request = service_usage.ListServicesRequest(parent=parent)
347
348
services = []
349
async for service in await client.list_services(request=request):
350
services.append(service)
351
352
print(f"Found {len(services)} services")
353
354
# Client is automatically closed when exiting the context
355
356
asyncio.run(async_context_example())
357
```