Skip to content

Instantly share code, notes, and snippets.

@thijstriemstra
Last active January 2, 2021 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thijstriemstra/5bbc71e1c7aff1ffb994eb0944a61cf8 to your computer and use it in GitHub Desktop.
Save thijstriemstra/5bbc71e1c7aff1ffb994eb0944a61cf8 to your computer and use it in GitHub Desktop.
Export Baikal addressbook using Python 3

This script loads an addressbook from a Baikal SQLite database file using SQLAlchemy, and writes the contacts to a single baikal.vcf file.

Install dependencies:

pip3 install SQLAlchemy vobject
from pathlib import Path
import vobject
from sqlalchemy import create_engine
CARDS = 'cards'
class BaikalDatabase(object):
cards = []
db_engine = None
def __init__(self, username='', password='', dbname=''):
engine_url = f'sqlite:///{dbname}'
self.db_engine = create_engine(engine_url)
def export_cards(self, table='', query=''):
with self.db_engine.connect() as connection:
try:
self.cards = []
result = connection.execute(query)
except Exception as e:
print(e)
else:
for row in result:
self.cards.append(vobject.readOne(row[1]))
result.close()
def export(self):
query = "SELECT id, carddata FROM {TBL_CARDS} WHERE " \
"addressbookid LIKE '1';".format(TBL_CARDS=CARDS)
self.export_cards(query=query)
def main():
# read cards
dbms = BaikalDatabase(dbname='db.sqlite')
dbms.export()
# save cards to single file
cfile = Path('baikal.vcf')
cfile.touch()
with cfile.open('w') as f:
for card in dbms.cards:
card.prettyPrint()
f.write(card.serialize())
print(f"Total cards: {len(dbms.cards)}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment