diff --git a/README.md b/README.md index e8aec76a..510e9156 100644 --- a/README.md +++ b/README.md @@ -58,25 +58,19 @@ class ZimTestArticle(ZimArticle): # Create a ZimTestArticle article article = ZimTestArticle() -print(article.content) # Write the articles + import uuid rnd_str = str(uuid.uuid1()) - test_zim_file_path = "/opt/python-libzim/tests/kiwix-test" -zim_creator = ZimCreator(test_zim_file_path + '-' + rnd_str + '.zim',main_page = "welcome",index_language= "eng", min_chunk_size= 2048) - -# Add article to zim file -zim_creator.add_article(article) - - -# Set mandatory metadata -if not zim_creator.mandatory_metadata_ok(): - zim_creator.update_metadata(creator='python-libzim',description='Created in python',name='Hola',publisher='Monadical',title='Test Zim') - -# Write article to zim file -zim_creator.finalize() +with ZimCreator(test_zim_file_path + '-' + rnd_str + '.zim') as zc: + zc.add_article(article) + if not zc.mandatory_metadata_ok(): + zc.update_metadata(creator='python-libzim', + description='Created in python', + name='Hola',publisher='Monadical', + title='Test Zim') ``` diff --git a/libzim/examples.py b/libzim/examples.py index dd3e5f7d..9c81386a 100644 --- a/libzim/examples.py +++ b/libzim/examples.py @@ -72,4 +72,18 @@ def get_data(self): print(zim_creator._get_metadata()) # Write articles to zim file -zim_creator.finalize() \ No newline at end of file +zim_creator.finalize() + + +# Example using context manager to ensure finalize is called. + +rnd_str = str(uuid.uuid1()) + +with ZimCreator(test_zim_file_path + '-' + rnd_str + '.zim') as zc: + zc.add_article(article) + zc.add_article(article2) + zc.update_metadata(creator='python-libzim', + description='Created in python', + name='Hola',publisher='Monadical', + title='Test Zim') + diff --git a/libzim/libzim.pyx b/libzim/libzim.pyx index 7cf47e75..baf84b13 100644 --- a/libzim/libzim.pyx +++ b/libzim/libzim.pyx @@ -8,7 +8,7 @@ from libcpp cimport bool from libcpp.memory cimport shared_ptr, make_shared import datetime - +from contextlib import contextmanager from collections import defaultdict ######################### @@ -172,7 +172,7 @@ cdef class ZimCreator: Attributes ---------- - *c_creator : zim.ZimCreator + *c_creator : zim.ZimCreatorWrapper a pointer to the C++ Creator object _finalized : bool flag if the creator was finalized @@ -224,6 +224,12 @@ cdef class ZimCreator: self._article_counter = defaultdict(int) self.update_metadata(date=datetime.date.today(), language= index_language) + def __enter__(self): + return self + + def __exit__(self, *args): + self.finalize() + def __dealloc__(self): del self.c_creator