From e63090756376611ab7ae56ed38a458cabdfae445 Mon Sep 17 00:00:00 2001 From: Joshua Harlow Date: Thu, 24 Apr 2014 17:01:38 -0700 Subject: [PATCH] Add a persistence backend fetching context manager Allow the persistence backends to be fetched using a new helper method that can be used as a context manager, it will fetch the backend, ensure it's upgraded and upon context manager exit will close the backend automatically. Change-Id: I1bf8e43dcce25c02823cca92e3e7ed3ef254a847 --- taskflow/persistence/backends/__init__.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/taskflow/persistence/backends/__init__.py b/taskflow/persistence/backends/__init__.py index 5cf30243..29c71d8c 100644 --- a/taskflow/persistence/backends/__init__.py +++ b/taskflow/persistence/backends/__init__.py @@ -14,6 +14,7 @@ # License for the specific language governing permissions and limitations # under the License. +import contextlib import logging import re @@ -53,3 +54,14 @@ def fetch(conf, namespace=BACKEND_NAMESPACE, **kwargs): return mgr.driver except RuntimeError as e: raise exc.NotFound("Could not find backend %s: %s" % (backend_name, e)) + + +@contextlib.contextmanager +def backend(conf, namespace=BACKEND_NAMESPACE, **kwargs): + """Fetches a persistence backend, ensures that it is upgraded and upon + context manager completion closes the backend. + """ + with contextlib.closing(fetch(conf, namespace=namespace, **kwargs)) as be: + with contextlib.closing(be.get_connection()) as conn: + conn.upgrade() + yield be