调用Anki API导出卡片信息时遇TypeError,请求排查解决
解决Anki API调用中的TypeError问题
问题现象
运行Anki API导出卡片信息的代码时,先后遇到两个错误:
- 初始报错:
TypeError: invoke() takes 1 positional argument but 2 were given
- 给
invoke函数添加self参数后报错:
TypeError: invoke() missing 1 required positional argument: 'action'
错误原因
- 第一个错误:
invoke函数定义用**params接收关键字参数,但调用invoke('cardsInfo', 1)时传入了位置参数1,不符合参数要求;同时Anki的cardsInfo接口要求参数为cards=[卡片ID列表],传参格式也不匹配。 - 第二个错误:
invoke是普通函数,不是类的方法,不需要self参数,添加后调用时未传入该参数导致报错。 - 原代码存在缩进错误:
if语句后的raise未缩进,会触发语法错误。
修复后的完整代码
import json import urllib.request def request(action, **params): return {'action': action, 'params': params, 'version': 6} def invoke(action, **params): requestJson = json.dumps(request(action, **params)).encode('utf-8') response = json.load(urllib.request.urlopen(urllib.request.Request('http://localhost:8765', requestJson))) if len(response) != 2: raise Exception('response has an unexpected number of fields') if 'error' not in response: raise Exception('response is missing required error field') if 'result' not in response: raise Exception('response is missing required result field') if response['error'] is not None: raise Exception(response['error']) return response['result'] # 获取卡组列表 result = invoke('deckNames') print('got list of decks: {}'.format(result)) # 获取指定卡片信息,按API要求以关键字参数传递卡片ID列表 Info = invoke('cardsInfo', cards=[1]) print(Info)
关键修复点
- 调用
cardsInfo时,必须以关键字参数cards=[卡片ID列表]传递参数,符合Anki API的参数规范。 - 修正
invoke函数内if语句的缩进问题,确保代码语法合法。 - 移除不必要的
self参数,普通函数无需该参数。
内容的提问来源于stack exchange,提问作者felix stevens
相关产品推荐
相关产品推荐

