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() |