创建会话模板 (v1)

在指定区域中创建新的 Dataproc 会话模板。

代码示例

Go

在尝试此示例之前,请按照《Managed Service for Apache Spark 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Managed Service for Apache Spark Go API 参考文档。

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


import (
	"context"
	"fmt"
	"io"

	dataproc "cloud.google.com/go/dataproc/v2/apiv1"
	"cloud.google.com/go/dataproc/v2/apiv1/dataprocpb"
	"google.golang.org/api/option"
)

// createSessionTemplate creates a Dataproc session template in the specified region.
func createSessionTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, sessionTemplateID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	sessionTemplate := &dataprocpb.SessionTemplate{
		Name:        fmt.Sprintf("projects/%s/locations/%s/sessionTemplates/%s", projectID, locationID, sessionTemplateID),
		Description: "Sample Dataproc Session Template",
		SessionConfig: &dataprocpb.SessionTemplate_JupyterSession{
			JupyterSession: &dataprocpb.JupyterConfig{
				Kernel:      dataprocpb.JupyterConfig_PYTHON,
				DisplayName: "Example Jupyter Session",
			},
		},
	}

	// Dataproc API calls require regional endpoints.
	endpoint := fmt.Sprintf("%s-dataproc.googleapis.com:443", locationID)
	client, err := dataproc.NewSessionTemplateControllerClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewSessionTemplateControllerClient failed: %w", err)
	}
	defer client.Close()

	req := &dataprocpb.CreateSessionTemplateRequest{
		Parent:          parent,
		SessionTemplate: sessionTemplate,
	}

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

	fmt.Fprintf(w, "Created session template: %s\n", resp.GetName())
	return nil
}

Java

在尝试此示例之前,请按照《Managed Service for Apache Spark 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Managed Service for Apache Spark Java API 参考文档。

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

import com.google.cloud.dataproc.v1.JupyterConfig;
import com.google.cloud.dataproc.v1.SessionTemplate;
import com.google.cloud.dataproc.v1.SessionTemplateControllerClient;
import com.google.cloud.dataproc.v1.SessionTemplateControllerSettings;
import java.io.IOException;

public class CreateSessionTemplate {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    String sessionTemplateId = "example-session-template-id";
    createSessionTemplate(projectId, locationId, sessionTemplateId);
  }

  public static void createSessionTemplate(
      String projectId, String locationId, String sessionTemplateId) throws IOException {
    // Configure regional endpoint for Dataproc control plane operations
    String endpoint = String.format("%s-dataproc.googleapis.com:443", locationId);
    SessionTemplateControllerSettings settings =
        SessionTemplateControllerSettings.newBuilder().setEndpoint(endpoint).build();

    try (SessionTemplateControllerClient client = SessionTemplateControllerClient.create(settings)) {
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);
      SessionTemplate sessionTemplate =
          SessionTemplate.newBuilder()
              .setName(String.format("%s/sessionTemplates/%s", parent, sessionTemplateId))
              .setDescription("Session template configured with Python Jupyter kernel")
              .setJupyterSession(
                  JupyterConfig.newBuilder()
                      .setKernel(JupyterConfig.Kernel.PYTHON)
                      .setDisplayName("Example Jupyter Session")
                      .build())
              .build();

      SessionTemplate response = client.createSessionTemplate(parent, sessionTemplate);
      System.out.println("Created session template: " + response.getName());
    }
  }
}

Node.js

在尝试此示例之前,请按照《Managed Service for Apache Spark 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Managed Service for Apache Spark Node.js API 参考文档。

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

'use strict';

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

/**
 * Creates a Dataproc session template.
 *
 * @param {string} projectId - The Google Cloud project ID where the session template is created.
 * @param {string} locationId - The Dataproc region where the session template resides (for example, 'us-central1').
 * @param {string} sessionTemplateId - The caller-specified identifier for the session template, conforming to RFC 1035 (1-63 characters, matching [a-z]([-a-z0-9]*[a-z0-9])?).
 */
async function createSessionTemplate(projectId, locationId, sessionTemplateId) {
  // Dataproc regional endpoints require configuring apiEndpoint with the matching region.
  const client = new SessionTemplateControllerClient({
    apiEndpoint: `${locationId}-dataproc.googleapis.com`,
  });

  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const sessionTemplate = {
      name: `${parent}/sessionTemplates/${sessionTemplateId}`,
      jupyterSession: {
        kernel: 'PYTHON',
        displayName: 'example-jupyter-session',
      },
    };

    const [response] = await client.createSessionTemplate({
      parent,
      sessionTemplate,
    });

    console.log(`Created session template: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Session template already exists: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createSessionTemplate };

Python

在尝试此示例之前,请按照《Managed Service for Apache Spark 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Managed Service for Apache Spark Python API 参考文档。

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

from google.api_core.client_options import ClientOptions
import google.api_core.exceptions
from google.cloud import dataproc_v1


def create_session_template(
    project_id: str, location_id: str, session_template_id: str
) -> None:
    """Creates a Dataproc session template.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The Dataproc region for the session template, for example us-central1.
        session_template_id: The caller-chosen identifier for the session template.
    """
    endpoint = f"{location_id}-dataproc.googleapis.com:443"
    client = dataproc_v1.SessionTemplateControllerClient(
        client_options=ClientOptions(api_endpoint=endpoint)
    )

    parent = f"projects/{project_id}/locations/{location_id}"
    session_template = dataproc_v1.SessionTemplate(
        name=f"projects/{project_id}/locations/{location_id}/sessionTemplates/{session_template_id}",
        jupyter_session=dataproc_v1.JupyterConfig(
            kernel=dataproc_v1.JupyterConfig.Kernel.PYTHON,
            display_name="example-jupyter-session",
        ),
    )

    try:
        response = client.create_session_template(
            parent=parent,
            session_template=session_template,
        )
        print(f"Created session template: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create session template: {error}")

后续步骤

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