|
1 | | -# Copyright 2026 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 | | - |
16 | | -import uuid |
17 | | - |
18 | | -try: |
19 | | - from google.api_core.gapic_v1.requests import setup_request_id # type: ignore |
20 | | -except ImportError: # pragma: NO COVER |
21 | | - # TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Remove this fallback when google-api-core >= 2.26.0 is the minimum required version. |
22 | | - def setup_request_id(request, field_name: str, is_proto3_optional: bool): # pragma: NO COVER |
23 | | - """Populate a UUID4 field in the request if it is not already set. |
24 | | -
|
25 | | - Args: |
26 | | - request (Union[google.protobuf.message.Message, dict]): The request object. |
27 | | - field_name (str): The name of the field to populate. |
28 | | - is_proto3_optional (bool): Whether the field is proto3 optional. |
29 | | - """ |
30 | | - request_id_val = str(uuid.uuid4()) |
31 | | - if isinstance(request, dict): |
32 | | - if is_proto3_optional: |
33 | | - if field_name not in request or request[field_name] is None: |
34 | | - request[field_name] = request_id_val |
35 | | - elif not request.get(field_name): |
36 | | - request[field_name] = request_id_val |
37 | | - return |
38 | | - |
39 | | - if is_proto3_optional: |
40 | | - try: |
41 | | - # Pure protobuf messages |
42 | | - if not request.HasField(field_name): |
43 | | - setattr(request, field_name, request_id_val) |
44 | | - except (AttributeError, ValueError): |
45 | | - # Proto-plus messages or other objects |
46 | | - if not getattr(request, field_name, None): |
47 | | - setattr(request, field_name, request_id_val) |
48 | | - else: |
49 | | - if not getattr(request, field_name, None): |
50 | | - setattr(request, field_name, request_id_val) |
0 commit comments