summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGauvain Pocentek <gauvain@pocentek.net>2018-02-05 14:21:14 +0100
committerGauvain Pocentek <gauvain@pocentek.net>2018-02-05 14:22:40 +0100
commitb4f03173f33ed8d214ddc20b4791ec11677f6bb1 (patch)
tree2bf8d58fff2068ace593c250e854eb9b4916f5cc
parent29bd81336828b72a47673c76862cb4b532401766 (diff)
downloadgitlab-b4f03173f33ed8d214ddc20b4791ec11677f6bb1.tar.gz
Gitlab can be used as context manager
Fixes #371
-rw-r--r--RELEASE_NOTES.rst6
-rw-r--r--docs/api-usage.rst17
-rw-r--r--gitlab/__init__.py6
3 files changed, 29 insertions, 0 deletions
diff --git a/RELEASE_NOTES.rst b/RELEASE_NOTES.rst
index 707b90d..da2545f 100644
--- a/RELEASE_NOTES.rst
+++ b/RELEASE_NOTES.rst
@@ -4,6 +4,12 @@ Release notes
This page describes important changes between python-gitlab releases.
+Changes from 1.2 to 1.3
+=======================
+
+* ``gitlab.Gitlab`` objects can be used as context managers in a ``with``
+ block.
+
Changes from 1.1 to 1.2
=======================
diff --git a/docs/api-usage.rst b/docs/api-usage.rst
index 3704591..5816b6d 100644
--- a/docs/api-usage.rst
+++ b/docs/api-usage.rst
@@ -274,6 +274,23 @@ HTTP requests to the Gitlab servers.
You can provide your own ``Session`` object with custom configuration when
you create a ``Gitlab`` object.
+Context manager
+---------------
+
+You can use ``Gitlab`` objects as context managers. This makes sure that the
+``requests.Session`` object associated with a ``Gitlab`` instance is always
+properly closed when you exit a ``with`` block:
+
+.. code-block:: python
+
+ with gitlab.Gitlab(host, token) as gl:
+ gl.projects.list()
+
+.. warning::
+
+ The context manager will also close the custom ``Session`` object you might
+ have used to build a ``Gitlab`` instance.
+
Proxy configuration
-------------------
diff --git a/gitlab/__init__.py b/gitlab/__init__.py
index 8a31a48..69629f8 100644
--- a/gitlab/__init__.py
+++ b/gitlab/__init__.py
@@ -147,6 +147,12 @@ class Gitlab(object):
manager = getattr(objects, cls_name)(self)
setattr(self, var_name, manager)
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ self.session.close()
+
def __getstate__(self):
state = self.__dict__.copy()
state.pop('_objects')