Skip to content

Commit b4f0317

Browse files
author
Gauvain Pocentek
committed
Gitlab can be used as context manager
Fixes python-gitlab#371
1 parent 29bd813 commit b4f0317

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

RELEASE_NOTES.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ Release notes
44

55
This page describes important changes between python-gitlab releases.
66

7+
Changes from 1.2 to 1.3
8+
=======================
9+
10+
* ``gitlab.Gitlab`` objects can be used as context managers in a ``with``
11+
block.
12+
713
Changes from 1.1 to 1.2
814
=======================
915

docs/api-usage.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,23 @@ HTTP requests to the Gitlab servers.
274274
You can provide your own ``Session`` object with custom configuration when
275275
you create a ``Gitlab`` object.
276276

277+
Context manager
278+
---------------
279+
280+
You can use ``Gitlab`` objects as context managers. This makes sure that the
281+
``requests.Session`` object associated with a ``Gitlab`` instance is always
282+
properly closed when you exit a ``with`` block:
283+
284+
.. code-block:: python
285+
286+
with gitlab.Gitlab(host, token) as gl:
287+
gl.projects.list()
288+
289+
.. warning::
290+
291+
The context manager will also close the custom ``Session`` object you might
292+
have used to build a ``Gitlab`` instance.
293+
277294
Proxy configuration
278295
-------------------
279296

gitlab/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,12 @@ def __init__(self, url, private_token=None, oauth_token=None, email=None,
147147
manager = getattr(objects, cls_name)(self)
148148
setattr(self, var_name, manager)
149149

150+
def __enter__(self):
151+
return self
152+
153+
def __exit__(self, *args):
154+
self.session.close()
155+
150156
def __getstate__(self):
151157
state = self.__dict__.copy()
152158
state.pop('_objects')

0 commit comments

Comments
 (0)