|
| 1 | +# Copyright 2022 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 | +# [START cloudoptimization_async_api] |
| 16 | + |
| 17 | +from google.api_core.exceptions import GoogleAPICallError |
| 18 | +from google.cloud import optimization_v1 |
| 19 | + |
| 20 | +# TODO(developer): Uncomment these variables before running the sample. |
| 21 | +# project_id= 'YOUR_PROJECT_ID' |
| 22 | +# request_file_name = 'YOUR_REQUEST_FILE_NAME' |
| 23 | +# request_model_gcs_path = 'gs://YOUR_PROJECT/YOUR_BUCKET/YOUR_REQUEST_MODEL_PATH' |
| 24 | +# model_solution_gcs_path = 'gs://YOUR_PROJECT/YOUR_BUCKET/YOUR_SOLUCTION_PATH' |
| 25 | + |
| 26 | + |
| 27 | +def call_async_api(project_id: str, request_model_gcs_path: str, model_solution_gcs_path_prefix: str) -> None: |
| 28 | + """Call the async api for fleet routing.""" |
| 29 | + # Use the default credentials for the environment to authenticate the client. |
| 30 | + fleet_routing_client = optimization_v1.FleetRoutingClient() |
| 31 | + request_file_name = "resources/async_request.json" |
| 32 | + |
| 33 | + with open(request_file_name, 'r') as f: |
| 34 | + fleet_routing_request = optimization_v1.BatchOptimizeToursRequest.from_json(f.read()) |
| 35 | + fleet_routing_request.parent = f"projects/{project_id}" |
| 36 | + for idx, mc in enumerate(fleet_routing_request.model_configs): |
| 37 | + mc.input_config.gcs_source.uri = request_model_gcs_path |
| 38 | + model_solution_gcs_path = f'{model_solution_gcs_path_prefix}_{idx}' |
| 39 | + mc.output_config.gcs_destination.uri = model_solution_gcs_path |
| 40 | + |
| 41 | + # The timeout argument for the gRPC call is independent from the `timeout` |
| 42 | + # field in the request's OptimizeToursRequest message(s). |
| 43 | + operation = fleet_routing_client.batch_optimize_tours(fleet_routing_request) |
| 44 | + print(operation.operation.name) |
| 45 | + |
| 46 | + try: |
| 47 | + # Block to wait for the job to finish. |
| 48 | + result = operation.result() |
| 49 | + print(result) |
| 50 | + # Do you stuff. |
| 51 | + except GoogleAPICallError: |
| 52 | + print(operation.operation.error) |
| 53 | + |
| 54 | + |
| 55 | +# [END cloudoptimization_async_api] |
0 commit comments