AnkiNoteTemplate/antp/ankiconnect.py

36 lines
1.1 KiB
Python
Raw Normal View History

2021-04-20 07:54:06 +00:00
# Taken from https://github.com/FooSoft/anki-connect
2021-11-27 11:54:42 +00:00
# Copyright: Ren Tatsumoto <tatsu at autistici.org>
# License: GNU GPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
__all__ = ['invoke', 'request_model_names']
2021-04-20 07:54:06 +00:00
import json
import urllib.request
2021-11-27 11:54:42 +00:00
from .common import ANTPError
2021-04-20 07:54:06 +00:00
def request(action, **params):
return {'action': action, 'params': params, 'version': 6}
def invoke(action, **params):
request_json = json.dumps(request(action, **params)).encode('utf-8')
2023-08-21 05:34:06 +00:00
response = json.load(urllib.request.urlopen(
urllib.request.Request('http://127.0.0.1:8765', request_json),
timeout=10
))
2021-04-20 07:54:06 +00:00
if len(response) != 2:
2021-11-27 11:54:42 +00:00
raise ANTPError('response has an unexpected number of fields')
2021-04-20 07:54:06 +00:00
if 'error' not in response:
2021-11-27 11:54:42 +00:00
raise ANTPError('response is missing required error field')
2021-04-20 07:54:06 +00:00
if 'result' not in response:
2021-11-27 11:54:42 +00:00
raise ANTPError('response is missing required result field')
2021-04-20 07:54:06 +00:00
if response['error'] is not None:
2021-11-27 11:54:42 +00:00
raise ANTPError(response['error'])
2021-04-20 07:54:06 +00:00
return response['result']
def request_model_names() -> list[str]:
return invoke('modelNames')