我正在使用anki-connect与间距重复软件Anki进行通信 在readme.md中,它使用以下命令获取卡组名称。
curl localhost:8765 -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"
它适用于我的Windows系统。
我如何使用python而不是cURL?
我试过这个,但没有运气。
import requests
r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
print(r.text)
答案 0 :(得分:1)
创建请求时,您应该:
Content-Type
标题Content-Type
标题您提供的curl
和python
示例都会向Content-Type: application/x-www-form-urlencoded
发送请求,默认值为{1}。差异是curl
传递字符串,python
传递数组。
让我们比较curl
和requests
以及真正发布的内容:
<强>卷曲强>
$ curl localhost -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"
接头:
Host: localhost
User-Agent: curl/7.52.1
Accept: */*
Content-Length: 37
Content-Type: application/x-www-form-urlencoded
发布数据:
[
'{"action": "deckNames", "version": 5}'
]
<强>的Python 强>
import requests
r = requests.post("http://127.0.0.1", data={'action': 'guiAddCards', 'version': 5})
print(r.text)
接头:
Host: 127.0.0.1
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.10.0
Content-Length: 28
Content-Type: application/x-www-form-urlencoded
发布数据:
[
'action' -> 'guiAddCards',
'version' -> '5',
]
如您所见,不正确的帖子数据格式会破坏您的应用。
可以肯定的是,应用程序会正确读取已发布的JSON数据,您应该提出这样的请求:
<强>卷曲强>
$ curl localhost:8765 -H 'Content-Type: application/json' -d '{"action": "deckNames", "version": 5}'
<强>的Python 强>
import requests
r = requests.post("http://127.0.0.1:8765", json={'action': 'guiAddCards', 'version': 5})
print(r.text)
答案 1 :(得分:0)
我在挖掘之后尝试过这种方法 任何人都可以分享原因。感谢。
import requests
import json
#r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5})
r = requests.post('http://localhost:8765', data=json.dumps({'action': 'guiAddCards', 'version': 5}))
print(r.text)
答案 2 :(得分:0)
这是对user2444791答案的回复。我无法回复评论,因为我没有评论的声誉(我是新的,请原谅礼仪的臀位!)
如果没有确切的错误消息,很难确定,但是......
查看Anki Connect API,它希望其POST-ed数据是一个包含JSON对象的字符串,而不是与该JSON对象等效的键/值字典。
每个请求都包含一个JSON编码的对象,其中包含一个动作,一个版本和一组上下文参数。
他们的示例代码(在Javascript中):xhr.send(JSON.stringify({action, version, params}));
可能就像以错误的格式发送数据一样简单。在第一个示例中,您将发送一个包含已解析的键/值对的字典。在第二个示例中,您将发送一个字符串供他们解析。