You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Anki API导出卡片信息时遇TypeError,请求排查解决

解决Anki API调用中的TypeError问题

问题现象

运行Anki API导出卡片信息的代码时,先后遇到两个错误:

  1. 初始报错:

TypeError: invoke() takes 1 positional argument but 2 were given

  1. 给invoke函数添加self参数后报错:

TypeError: invoke() missing 1 required positional argument: 'action'

错误原因

  1. 第一个错误:invoke函数定义用**params接收关键字参数,但调用invoke('cardsInfo', 1)时传入了位置参数1,不符合参数要求;同时Anki的cardsInfo接口要求参数为cards=[卡片ID列表],传参格式也不匹配。
  2. 第二个错误:invoke是普通函数,不是类的方法,不需要self参数,添加后调用时未传入该参数导致报错。
  3. 原代码存在缩进错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:15:17