Skip to content

Commit be423d3

Browse files
committed
Async!
1 parent be25c16 commit be423d3

File tree

10 files changed

+466
-196
lines changed

10 files changed

+466
-196
lines changed

ASYNC_README.md

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
# Асинхронный GitLab клиент
2+
3+
Этот модуль предоставляет асинхронный клиент для работы с GitLab API, используя HTTPX для HTTP запросов.
4+
5+
## Особенности
6+
7+
- **Полностью асинхронный**: Все HTTP запросы выполняются асинхронно
8+
- **Простота использования**: Каждый запрос создает свой собственный `AsyncClient` и автоматически закрывает его
9+
- **Совместимость**: Наследует от базового класса `Gitlab` и поддерживает все стандартные методы
10+
- **Обработка ошибок**: Встроенная обработка ошибок аутентификации и HTTP ошибок
11+
12+
## Установка
13+
14+
Убедитесь, что у вас установлен `httpx`:
15+
16+
```bash
17+
pip install httpx
18+
```
19+
20+
## Использование
21+
22+
### Базовое использование
23+
24+
```python
25+
import asyncio
26+
from gitlab import AsyncGitlab
27+
28+
async def main():
29+
# Создаем асинхронный клиент
30+
gl = AsyncGitlab(
31+
url="https://gitlab.com",
32+
private_token="your-token-here"
33+
)
34+
35+
# Выполняем запросы
36+
response = await gl.get("/user")
37+
print(f"Пользователь: {response['text']}")
38+
39+
# Получаем список проектов
40+
projects = await gl.get("/projects", params={"per_page": 5})
41+
print(f"Проекты: {projects['text']}")
42+
43+
# Запускаем
44+
asyncio.run(main())
45+
```
46+
47+
### Доступные методы
48+
49+
Клиент поддерживает все основные HTTP методы:
50+
51+
```python
52+
# GET запрос
53+
response = await gl.get("/projects")
54+
55+
# POST запрос
56+
response = await gl.post("/projects", data={"name": "new-project"})
57+
58+
# PUT запрос
59+
response = await gl.put("/projects/123", data={"description": "Updated"})
60+
61+
# DELETE запрос
62+
response = await gl.delete("/projects/123")
63+
64+
# PATCH запрос
65+
response = await gl.patch("/projects/123", data={"name": "new-name"})
66+
```
67+
68+
### Параметры запросов
69+
70+
```python
71+
# С параметрами запроса
72+
response = await gl.get("/projects", params={
73+
"per_page": 10,
74+
"page": 1,
75+
"order_by": "created_at"
76+
})
77+
78+
# С заголовками
79+
response = await gl.get("/projects", headers={
80+
"Custom-Header": "value"
81+
})
82+
83+
# С таймаутом
84+
response = await gl.get("/projects", timeout=30.0)
85+
```
86+
87+
### Обработка ошибок
88+
89+
```python
90+
try:
91+
response = await gl.get("/user")
92+
print(f"Успех: {response['text']}")
93+
except GitlabAuthenticationError as e:
94+
print(f"Ошибка аутентификации: {e}")
95+
except GitlabHttpError as e:
96+
print(f"HTTP ошибка: {e}")
97+
except Exception as e:
98+
print(f"Общая ошибка: {e}")
99+
```
100+
101+
### Аутентификация
102+
103+
Поддерживаются различные типы аутентификации:
104+
105+
```python
106+
# Private Token
107+
gl = AsyncGitlab(
108+
url="https://gitlab.com",
109+
private_token="your-private-token"
110+
)
111+
112+
# OAuth Token
113+
gl = AsyncGitlab(
114+
url="https://gitlab.com",
115+
oauth_token="your-oauth-token"
116+
)
117+
118+
# Job Token (для CI/CD)
119+
gl = AsyncGitlab(
120+
url="https://gitlab.com",
121+
job_token="your-job-token"
122+
)
123+
```
124+
125+
### Параллельные запросы
126+
127+
```python
128+
async def fetch_data():
129+
gl = AsyncGitlab(
130+
url="https://gitlab.com",
131+
private_token="your-token"
132+
)
133+
134+
# Выполняем несколько запросов параллельно
135+
tasks = [
136+
gl.get("/projects"),
137+
gl.get("/users"),
138+
gl.get("/groups")
139+
]
140+
141+
results = await asyncio.gather(*tasks)
142+
return results
143+
144+
# Запускаем
145+
projects, users, groups = await fetch_data()
146+
```
147+
148+
## Архитектура
149+
150+
### HTTPX Backend
151+
152+
Клиент использует кастомный HTTPX backend (`HTTPXBackend`), который:
153+
154+
1. Создает новый `AsyncClient` для каждого запроса
155+
2. Автоматически закрывает соединение после выполнения запроса
156+
3. Возвращает стандартизированный ответ в виде словаря
157+
158+
### Структура ответа
159+
160+
Каждый HTTP запрос возвращает словарь с полями:
161+
162+
```python
163+
{
164+
"status_code": 200,
165+
"headers": {"content-type": "application/json", ...},
166+
"content": b'{"id": 1, "name": "project"}',
167+
"text": '{"id": 1, "name": "project"}'
168+
}
169+
```
170+
171+
### Обработка ошибок
172+
173+
- **401 Unauthorized**: Вызывает `GitlabAuthenticationError`
174+
- **4xx/5xx ошибки**: Вызывают `GitlabHttpError`
175+
- **Сетевые ошибки**: Оборачиваются в `GitlabHttpError`
176+
177+
## Преимущества
178+
179+
1. **Простота**: Не нужно управлять жизненным циклом соединения
180+
2. **Надежность**: Каждый запрос изолирован
181+
3. **Производительность**: HTTPX обеспечивает высокую производительность
182+
4. **Совместимость**: Работает с существующим кодом python-gitlab
183+
184+
## Ограничения
185+
186+
- Только API версии 4
187+
- Базовые HTTP методы (GET, POST, PUT, DELETE, PATCH)
188+
- Нет встроенной поддержки пагинации
189+
- Нет поддержки GraphQL
190+
191+
## Примеры
192+
193+
Смотрите файл `examples/async_example.py` для полных примеров использования.

README.rst

Lines changed: 1 addition & 190 deletions
Original file line numberDiff line numberDiff line change
@@ -1,190 +1 @@
1-
python-gitlab
2-
=============
3-
4-
.. image:: https://github.com/python-gitlab/python-gitlab/workflows/Test/badge.svg
5-
:target: https://github.com/python-gitlab/python-gitlab/actions
6-
7-
.. image:: https://badge.fury.io/py/python-gitlab.svg
8-
:target: https://badge.fury.io/py/python-gitlab
9-
10-
.. image:: https://readthedocs.org/projects/python-gitlab/badge/?version=latest
11-
:target: https://python-gitlab.readthedocs.org/en/latest/?badge=latest
12-
13-
.. image:: https://codecov.io/github/python-gitlab/python-gitlab/coverage.svg?branch=main
14-
:target: https://codecov.io/github/python-gitlab/python-gitlab?branch=main
15-
16-
.. image:: https://img.shields.io/pypi/pyversions/python-gitlab.svg
17-
:target: https://pypi.python.org/pypi/python-gitlab
18-
19-
.. image:: https://img.shields.io/gitter/room/python-gitlab/Lobby.svg
20-
:target: https://gitter.im/python-gitlab/Lobby
21-
22-
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
23-
:target: https://github.com/python/black
24-
25-
.. image:: https://img.shields.io/github/license/python-gitlab/python-gitlab
26-
:target: https://github.com/python-gitlab/python-gitlab/blob/main/COPYING
27-
28-
``python-gitlab`` is a Python package providing access to the GitLab APIs.
29-
30-
It includes a client for GitLab's v4 REST API, synchronous and asynchronous GraphQL API
31-
clients, as well as a CLI tool (``gitlab``) wrapping REST API endpoints.
32-
33-
.. _features:
34-
35-
Features
36-
--------
37-
38-
``python-gitlab`` enables you to:
39-
40-
* write Pythonic code to manage your GitLab resources.
41-
* pass arbitrary parameters to the GitLab API. Simply follow GitLab's docs
42-
on what parameters are available.
43-
* use a synchronous or asynchronous client when using the GraphQL API.
44-
* access arbitrary endpoints as soon as they are available on GitLab, by using
45-
lower-level API methods.
46-
* use persistent requests sessions for authentication, proxy and certificate handling.
47-
* handle smart retries on network and server errors, with rate-limit handling.
48-
* flexible handling of paginated responses, including lazy iterators.
49-
* automatically URL-encode paths and parameters where needed.
50-
* automatically convert some complex data structures to API attribute types
51-
* merge configuration from config files, environment variables and arguments.
52-
53-
Installation
54-
------------
55-
56-
As of 5.0.0, ``python-gitlab`` is compatible with Python 3.9+.
57-
58-
Use ``pip`` to install the latest stable version of ``python-gitlab``:
59-
60-
.. code-block:: console
61-
62-
$ pip install --upgrade python-gitlab
63-
64-
The current development version is available on both `GitHub.com
65-
<https://github.com/python-gitlab/python-gitlab>`__ and `GitLab.com
66-
<https://gitlab.com/python-gitlab/python-gitlab>`__, and can be
67-
installed directly from the git repository:
68-
69-
.. code-block:: console
70-
71-
$ pip install git+https://github.com/python-gitlab/python-gitlab.git
72-
73-
From GitLab:
74-
75-
.. code-block:: console
76-
77-
$ pip install git+https://gitlab.com/python-gitlab/python-gitlab.git
78-
79-
Using the docker images
80-
-----------------------
81-
82-
``python-gitlab`` provides Docker images in two flavors, based on the Alpine and Debian slim
83-
python `base images <https://hub.docker.com/_/python>`__. The default tag is ``alpine``,
84-
but you can explicitly use the alias (see below).
85-
86-
The alpine image is smaller, but you may want to use the Debian-based slim tag (currently
87-
based on ``-slim-bullseye``) if you are running into issues or need a more complete environment
88-
with a bash shell, such as in CI jobs.
89-
90-
The images are published on the GitLab registry, for example:
91-
92-
* ``registry.gitlab.com/python-gitlab/python-gitlab:latest`` (latest, alpine alias)
93-
* ``registry.gitlab.com/python-gitlab/python-gitlab:alpine`` (latest alpine)
94-
* ``registry.gitlab.com/python-gitlab/python-gitlab:slim-bullseye`` (latest slim-bullseye)
95-
* ``registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0`` (alpine alias)
96-
* ``registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0-alpine``
97-
* ``registry.gitlab.com/python-gitlab/python-gitlab:v3.2.0-slim-bullseye``
98-
99-
You can run the Docker image directly from the GitLab registry:
100-
101-
.. code-block:: console
102-
103-
$ docker run -it --rm registry.gitlab.com/python-gitlab/python-gitlab:latest <command> ...
104-
105-
For example, to get a project on GitLab.com (without authentication):
106-
107-
.. code-block:: console
108-
109-
$ docker run -it --rm registry.gitlab.com/python-gitlab/python-gitlab:latest project get --id gitlab-org/gitlab
110-
111-
You can also mount your own config file:
112-
113-
.. code-block:: console
114-
115-
$ docker run -it --rm -v /path/to/python-gitlab.cfg:/etc/python-gitlab.cfg registry.gitlab.com/python-gitlab/python-gitlab:latest <command> ...
116-
117-
Usage inside GitLab CI
118-
~~~~~~~~~~~~~~~~~~~~~~
119-
120-
If you want to use the Docker image directly inside your GitLab CI as an ``image``, you will need to override
121-
the ``entrypoint``, `as noted in the official GitLab documentation <https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#override-the-entrypoint-of-an-image>`__:
122-
123-
.. code-block:: yaml
124-
125-
Job Name:
126-
image:
127-
name: registry.gitlab.com/python-gitlab/python-gitlab:latest
128-
entrypoint: [""]
129-
before_script:
130-
gitlab --version
131-
script:
132-
gitlab <command>
133-
134-
Building the image
135-
~~~~~~~~~~~~~~~~~~
136-
137-
To build your own image from this repository, run:
138-
139-
.. code-block:: console
140-
141-
$ docker build -t python-gitlab:latest .
142-
143-
Run your own image:
144-
145-
.. code-block:: console
146-
147-
$ docker run -it --rm python-gitlab:latest <command> ...
148-
149-
Build a Debian slim-based image:
150-
151-
.. code-block:: console
152-
153-
$ docker build -t python-gitlab:latest --build-arg PYTHON_FLAVOR=slim-bullseye .
154-
155-
Bug reports
156-
-----------
157-
158-
Please report bugs and feature requests at
159-
https://github.com/python-gitlab/python-gitlab/issues.
160-
161-
Gitter Community Chat
162-
---------------------
163-
164-
We have a `gitter <https://gitter.im/python-gitlab/Lobby>`_ community chat
165-
available at https://gitter.im/python-gitlab/Lobby, which you can also
166-
directly access via the Open Chat button below.
167-
168-
If you have a simple question, the community might be able to help already,
169-
without you opening an issue. If you regularly use python-gitlab, we also
170-
encourage you to join and participate. You might discover new ideas and
171-
use cases yourself!
172-
173-
Documentation
174-
-------------
175-
176-
The full documentation for CLI and API is available on `readthedocs
177-
<http://python-gitlab.readthedocs.org/en/stable/>`_.
178-
179-
Build the docs
180-
~~~~~~~~~~~~~~
181-
182-
We use ``tox`` to manage our environment and build the documentation::
183-
184-
pip install tox
185-
tox -e docs
186-
187-
Contributing
188-
------------
189-
190-
For guidelines for contributing to ``python-gitlab``, refer to `CONTRIBUTING.rst <https://github.com/python-gitlab/python-gitlab/blob/main/CONTRIBUTING.rst>`_.
1+
AI Generated fork

0 commit comments

Comments
 (0)