【问题标题】:Python3 retrying with tenacity (w/out decorators) gives error claiming "missing arguments" when using gspreadPython3 在使用 gspread 时重试坚韧(不带装饰器)会出现错误,声称“缺少参数”
【发布时间】:2020-06-06 20:52:28
【问题描述】:

我正在尝试使用坚韧模块来避免来自 gspread 的频繁请求错误 (APIErrors)。我了解tenacity 使用装饰器的常见示例,但我想使用tenacity 的Retrying() 函数,所以我可以让它重试gspread 的电子表格单元格更新方法sheet.update_acell()。

由于某种原因,使用sheet.update_acell() 重试实际上并没有将参数“提供”给函数(或其他东西)。然而,一个人为的多参数示例非常有效。

我的代码(除了导入和谷歌 API 凭证):

# gspread authorization
gs_client = gspread.authorize(creds)
workbook = gs_client.open_by_key(sheet_key)
sheet = workbook.sheet1

ret = tenacity.Retrying(stop=tenacity.stop_after_attempt(30),
                        wait=tenacity.wait_exponential(multiplier=0.5, max=60))

# contrived example
def retry_example(arg0, arg1):
    print(arg0, arg1)
ret.call(retry_example,'foo','bar')  #works perfectly

# gspread example
ret.call(sheet.update_acell(),'A1',1)  #doesn't work, the arguments aren't found

输出:

foo bar
Traceback (most recent call last):
  File "c:/Users/.../tenacitytest.py", line 28, in <module>
    ret.call(sheet.update_acell(),'A1',1)
TypeError: update_acell() missing 2 required positional arguments: 'label' and 'value'

在没有韧性的情况下运行 gspread 的东西可以正常工作,所以我确定我正确地调用了 update_acell()。

我觉得这可能与 gspread 的 update_acell() 是一种方法的事实有关,不像 example_func()? 任何帮助将不胜感激。

【问题讨论】:

  • 可以这样试试吗? ret.call(sheet.update_acell,'A1',1)

标签: python python-3.x google-api gspread python-tenacity


【解决方案1】:

您不应在 Retrying 调用中使用括号。您应该传递如下参数

希望这会奏效;)

ret.call(sheet.update_acell,'A1',1)

示例:

from tenacity import Retrying, stop_after_attempt

def foo(arg1, arg2):
    print('Arguments are: {} {}'.format(arg1, arg2))
    raise Exception('Throwing Exception')

def bar(max_attempts=3):
    retryer = Retrying(stop=stop_after_attempt(max_attempts), reraise=True)
    retryer(foo, 'my arg1', 'my arg2')

让我们试试错误场景:

>>> from tenacity import Retrying, stop_after_attempt
>>>
>>> def foo(arg1, arg2):
...     print('Arguments are: {} {}'.format(arg1, arg2))
...     raise Exception('Throwing Exception')
...
>>> def bar(max_attempts=3):
...     retryer = Retrying(stop=stop_after_attempt(max_attempts), reraise=True)
...     retryer(foo(), 'my arg1', 'my arg2')
...
>>> bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in bar
TypeError: foo() missing 2 required positional arguments: 'arg1' and 'arg2'
>>>   

【讨论】:

  • 哇,盯着几行代码看了一个小时后,我觉得有点愚蠢。感谢您这么快回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2021-02-22
  • 2022-06-28
  • 2020-07-05
相关资源
最近更新 更多