ImportError: cannot import name 'tasks_v2' from 'google.cloud'

ImportError: cannot import name 'tasks_v2' from 'google.cloud'

我正在尝试使用 GCP 文档中提供的 Google Cloud Tasks 代码示例: https://cloud.google.com/tasks/docs/creating-http-target-tasks(见下面的代码)。但是,从文档中不清楚我需要哪个包才能工作。有什么想法吗?

但是,我收到以下错误。

ImportError: cannot import name 'tasks_v2' from 'google.cloud'

代码示例:

from google.cloud import tasks_v2
from google.protobuf import timestamp_pb2

# Create a client.
client = tasks_v2.CloudTasksClient()

# TODO(developer): Uncomment these lines and replace with your values.
# project = 'my-project-id'
# queue = 'my-appengine-queue'
# location = 'us-central1'
# payload = 'hello'

# Construct the fully qualified queue name.
parent = client.queue_path(project, location, queue)

# Construct the request body.
task = {
        'app_engine_http_request': {  # Specify the type of request.
            'http_method': 'POST',
            'relative_uri': '/example_task_handler'
        }
}
if payload is not None:
    # The API expects a payload of type bytes.
    converted_payload = payload.encode()

    # Add the payload to the request.
    task['app_engine_http_request']['body'] = converted_payload

if in_seconds is not None:
    # Convert "seconds from now" into an rfc3339 datetime string.
    d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)

    # Create Timestamp protobuf.
    timestamp = timestamp_pb2.Timestamp()
    timestamp.FromDatetime(d)

    # Add the timestamp to the tasks.
    task['schedule_time'] = timestamp

# Use the client to build and send the task.
response = client.create_task(parent, task)

print('Created task {}'.format(response.name))
return response

这对我有用:

pip3 install -U google-cloud-tasks

如果您在为其他 GCP 服务导入包时遇到任何问题,这是一个很好的资源: https://github.com/googleapis/google-cloud-python. The links point straight to the relevant package names on pypi.org.

当遵循 GCP 文档上的任何指南时,转到 github 存储库并搜索 requirements.txt 文件,这里将是所有使用的依赖项以及版本。

对于creating http task the requirements file would be this one.

google-cloud-tasks==2.0.0

这正是您要查找的依赖项和版本