From 18fb69dff80b06def109a876266bcaf5bb087449 Mon Sep 17 00:00:00 2001 From: Davte Date: Wed, 5 Jun 2019 12:49:47 +0200 Subject: [PATCH] Instantiate dataset.Database object once and return it without re-instantiating it. --- davtelepot/__init__.py | 2 +- davtelepot/custombot.py | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/davtelepot/__init__.py b/davtelepot/__init__.py index a364b47..db159c1 100644 --- a/davtelepot/__init__.py +++ b/davtelepot/__init__.py @@ -7,7 +7,7 @@ __author__ = "Davide Testa" __email__ = "davide@davte.it" __credits__ = "Marco Origlia" __license__ = "GNU General Public License v3.0" -__version__ = "1.5.4" +__version__ = "1.5.5" __maintainer__ = "Davide Testa" __contact__ = "t.me/davte" diff --git a/davtelepot/custombot.py b/davtelepot/custombot.py index eb662ab..56c2bc7 100644 --- a/davtelepot/custombot.py +++ b/davtelepot/custombot.py @@ -166,8 +166,10 @@ class Bot(telepot.aio.Bot, Gettable): name=db_name, ext='.db' if not db_name.endswith('.db') else '' ) + self._database = dataset.connect(self.db_url) else: self._db_url = None + self._database = None self._unauthorized_message = None self.authorization_function = lambda update, authorization_level: True self.get_chat_id = lambda update: ( @@ -222,12 +224,20 @@ class Bot(telepot.aio.Bot, Gettable): @property def db(self): - """Connect to bot's database. + """Return the dataset.Database instance related to `self`. - It must be used inside a with statement: `with bot.db as db` + To start a transaction with bot's database, use a with statement: + ```python3 + with bot.db as db: + db['your_table'].insert( + dict( + name='John', + age=45 + ) + ) + ``` """ - if self.db_url: - return dataset.connect(self.db_url) + return self._database @property def default_keyboard(self):