停用处理器 (v1)

停用现有 Document AI 处理器。

代码示例

Go

如需了解详情,请参阅 Document AI Go API 参考文档。

如需向 Document AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。


import (
	"context"
	"fmt"
	"io"

	documentai "cloud.google.com/go/documentai/apiv1beta3"
	"cloud.google.com/go/documentai/apiv1beta3/documentaipb"
	"google.golang.org/api/option"
)

// disableProcessor disables an existing processor.
func disableProcessor(ctx context.Context, w io.Writer, projectID string, locationID string, processorID string) error {
	name := fmt.Sprintf("projects/%s/locations/%s/processors/%s", projectID, locationID, processorID)

	endpoint := fmt.Sprintf("%s-documentai.googleapis.com:443", locationID)
	client, err := documentai.NewDocumentProcessorClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewDocumentProcessorClient: %w", err)
	}
	defer client.Close()

	req := &documentaipb.DisableProcessorRequest{
		Name: name,
	}

	op, err := client.DisableProcessor(ctx, req)
	if err != nil {
		return fmt.Errorf("DisableProcessor: %w", err)
	}

	if _, err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Processor disabled: %s\n", name)

	return nil
}

Java

如需了解详情,请参阅 Document AI Java API 参考文档。

如需向 Document AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

import com.google.cloud.documentai.v1.DisableProcessorRequest;
import com.google.cloud.documentai.v1.DisableProcessorResponse;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.ProcessorName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DisableProcessor {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String processorId = "example-processor_id";
    disableProcessor(projectId, locationId, processorId);
  }

  public static void disableProcessor(String projectId, String locationId, String processorId)
      throws Exception {
    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create()) {
      String name = ProcessorName.of(projectId, locationId, processorId).toString();

      DisableProcessorRequest request =
          DisableProcessorRequest.newBuilder().setName(name).build();

      // DisableProcessor is a long-running operation; wait for completion.
      DisableProcessorResponse response =
          client.disableProcessorAsync(request).get(2, TimeUnit.MINUTES);

      System.out.printf("Processor disabled successfully: %s%n", name);
    }
  }
}

Node.js

如需了解详情,请参阅 Document AI Node.js API 参考文档。

如需向 Document AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

'use strict';

const {DocumentProcessorServiceClient} = require('@google-cloud/documentai');
const {status} = require('@grpc/grpc-js');

const client = new DocumentProcessorServiceClient();

/**
 * Disables a Document AI processor.
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud location ID (for example, 'us' or 'eu').
 * @param {string} processorId - The server-generated ID of the processor to disable.
 */
async function disableProcessor(projectId, locationId, processorId) {
  try {
    const name = `projects/${projectId}/locations/${locationId}/processors/${processorId}`;
    const request = {
      name,
    };

    // DisableProcessor initiates a long-running operation.
    const [operation] = await client.disableProcessor(request);
    await operation.promise();

    console.log(`Processor disabled successfully: ${name}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Processor not found: ${err.message}`);
    } else if (err.code === status.FAILED_PRECONDITION) {
      console.error(`Processor cannot be disabled: ${err.message}`);
    } else if (err.code) {
      console.error(`RPC error [${err.code}]: ${err.message}`);
    } else {
      console.error(`Error: ${err.message}`);
    }
  }
}

module.exports = { disableProcessor };

Python

如需了解详情,请参阅 Document AI Python API 参考文档。

如需向 Document AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

import google.api_core.exceptions
from google.cloud import documentai_v1

client = documentai_v1.DocumentProcessorServiceClient()


def disable_processor(project_id: str, location_id: str, processor_id: str) -> None:
    """Disables a Document AI processor.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud location or region for the processor (for example, 'us' or 'eu').
        processor_id: The ID of the processor to disable.
    """
    name = client.processor_path(project_id, location_id, processor_id)

    request = documentai_v1.DisableProcessorRequest(name=name)

    try:
        operation = client.disable_processor(request=request)
        operation.result()
        print(f"Disabled processor: {name}")
    except (
        google.api_core.exceptions.NotFound,
        google.api_core.exceptions.FailedPrecondition,
        google.api_core.exceptions.GoogleAPICallError,
    ) as error:
        print(f"Failed to disable processor: {error}")

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器。