遇到错误TypeError:create_task需要1到2个位置参数,但是在创建Google Cloud Task时给出了3个

问题描述

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)

当我尝试创建Google Cloud Task时,始终出现以下错误。 使用的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

解决方法

我也发生了同样的事情(在实时服务器:/上)。事实证明,Cloud Tasks库在2.0.0版中已发生重大变化。您可以阅读what you need to do to upgrade here

您的问题在这一行:

client.create_task(parent,task)

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

client.create_task(parent=parent,task=task)

编辑:我自己完成了这项工作,现在来看您的代码,您还必须更改以下内容:

# 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)

# Before
'http_method': 'POST',# After
'http_method': tasks_v2.HttpMethod.POST,

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...