安全创建和编辑*.apkg和*.anki2
ankisync2的Python项目详细描述
ankisync 2
*.apkg和*.anki2文件结构非常简单,但有一些不完整的怪癖。
*.apkg file structure是至少包含两个文件的zip。
.
├── example
│ ├── example.anki2
│ ├── media
│ ├── 1 # Media files with the names masked as integers
│ ├── 2
│ ├── 3
| └── ...
└── example.apkg
*.anki2是一个禁用外键的sqlite文件,使用some JSON schemas而不是some tables
另外,*.anki2在^{
media
文件是至少包含一个字符串{}
的文本文件,它实际上是一个包含键(stringified int)和值(filenames)的字典。
用法
如果不存在,则创建一些extra tables。
fromankisync2.ankiimportAnki2,Apkgapkg=Apkg("example.apkg")# Or Apkg("example/") also works, otherwise the folder named 'example' will be created.apkg.db.execute_sql(SQL,PARAMS)apkg.zip(output="example1.apkg")
我也支持添加媒体。
apkg.add_media("path/to/media.jpg")
要找到想要的卡和媒体,请遍历Apkg
和Apkg.iter_media
对象。
iter_apkg=iter(apkg)foriinrange(5):print(next(iter_apkg))
创建新的*.apkg
您可以使用任何自定义文件名通过Apkg
创建一个新的*.apkg(通过Anki2()
*.anki2)。首先需要创建创建*.apkg所需的文件夹。
fromankisync2.ankiimportApkgapkg=Apkg("example")# Create example folder
之后,APKG将需要至少一张卡,该卡连接到至少一张便笺、一个模型、一个模板和一个卡组;应按此顺序创建。
- 模型,甲板
- 模板,注意
- 卡
fromankisync2importdbm=db.Models.create(name="foo",flds=["field1","field2"])d=db.Decks.create(name="bar::baz")t=[db.Templates.create(name="fwd",mid=m.id,qfmt="{{field1}}",afmt="{{field2}}"),db.Templates.create(name="bwd",mid=m.id,qfmt="{{field2}}",afmt="{{field1}}")]n=db.Notes.create(mid=m.id,flds=["data1","<img src='media.jpg'>"],tags=["tag1","tag2"])c=[db.Cards.create(nid=n.id,did=d.id,ord=i)fori,_inenumerate(t)]
还可以添加与sqlite数据库无关的媒体。
apkg.add_media("path/to/media.jpg")
最后,用
完成apkg.zip(output="example1.apkg")apkg.close()
更新*.apkg
这也是可能的,通过将db.Notes.data
修改为sqlite_ext.JSONField
,使用peewee.signals
。
它现在非常简单,
fromankisync2.ankiimportApkgfromankisync2importdbapkg=Apkg("example1.apkg")fornindb.Notes.filter(db.Notes.data["field1"]=="data1"):n.data["field3"]="data2"n.save()apkg.close()
json模式的Col.models
、Col.decks
、Col.conf
和Col.dconf
我已经在/ankisync2/builder.py为这个创建了dataclasses
。要序列化它,请使用dataclasses.asdict
或
fromankisync2.utilimportDataclassJSONEncoderimportjsonjson.dumps(dataclassObject,cls=DataclassJSONEncoder)
有关如何工作的示例,请参见/ankisync2/anki.py#L56
使用peewee
框架
您还可以使用peewee
orm框架;并且ArrayField、X1fField和JSONField将是自动的。您可以直接使用数据类和列表,而不必先将它们转换为字符串。
示例
安装
pip install ankisync2