获取错误类型错误:create_task() 需要 1 到 2 个位置参数,但在创建谷歌云任务时给出了 3 个

Avi*_*vin 2 python queue python-3.x google-cloud-platform google-cloud-tasks

from google.cloud import tasks_v2

import json


GCP_PROJECT='test'
GCP_LOCATION='europe-west6'


def enqueue_task(queue_name, payload, process_url):
  client = tasks_v2.CloudTasksClient()
  parent = client.queue_path(GCP_PROJECT, GCP_LOCATION, queue_name)

  task = {
    'app_engine_http_request': {
      'http_method': 'POST',
      'relative_uri': process_url
    }
  }

  if payload is None:
    return False

  payload = json.dumps(payload)
  converted_payload = payload.encode()

  task['app_engine_http_request']['body'] = converted_payload
  return client.create_task(parent, task)
Run Code Online (Sandbox Code Playgroud)

当我尝试创建 Google Cloud 任务时,我不断收到以下错误。使用的 Google App Engine 运行时是 python38。它工作正常,但在使用 gcp CLI 部署后突然无法正常工作。

Traceback (most recent call last):
  File "/layers/google.python.pip/pip/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/layers/google.python.pip/pip/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/layers/google.python.pip/pip/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/layers/google.python.pip/pip/flask/_compat.py", line 39, in reraise
    raise value
  File "/layers/google.python.pip/pip/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/layers/google.python.pip/pip/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/srv/main.py", line 153, in sync_request
    queue_response = queues.enqueue_task(
  File "/srv/queues.py", line 28, in enqueue_task
    return client.create_task(parent, task)
TypeError: create_task() takes from 1 to 2 positional arguments but 3 were given
Run Code Online (Sandbox Code Playgroud)

Jan*_*iec 5

同样的事情刚刚发生在我身上(在实时服务器上:/)。事实证明,Cloud Tasks 库在 2.0.0 版本中发生了重大变化。您可以在此处阅读升级所需的操作

你的问题在这一行:

client.create_task(parent, task)
Run Code Online (Sandbox Code Playgroud)

更新后的库需要使用字典作为位置参数或使用关键字参数。所以这应该解决它:

client.create_task(parent=parent, task=task)
Run Code Online (Sandbox Code Playgroud)

编辑:既然我已经为自己完成了这项工作,请查看您的代码,您还必须更改以下内容:

# Before
parent = client.queue_path(GCP_PROJECT, GCP_LOCATION, queue_name)
# After
parent = client.queue_path(project=GCP_PROJECT, location=GCP_LOCATION, queue=queue_name)
Run Code Online (Sandbox Code Playgroud)

# Before
'http_method': 'POST',
# After
'http_method': tasks_v2.HttpMethod.POST,
Run Code Online (Sandbox Code Playgroud)