3laba/cod/gitea_api_client.py
2026-05-08 11:24:20 +03:00

207 lines
7.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# gitea_api_client.py
import os
import requests
import json
import logging
from pathlib import Path
# Загружаем .env файл для PyCharm
try:
from dotenv import load_dotenv
# Ищем .env файл в текущей директории
env_path = Path('..') / '.env'
if env_path.exists():
load_dotenv()
logging.info("Загружен .env файл")
else:
logging.warning(".env файл не найден, используем системные переменные")
except ImportError:
logging.warning("python-dotenv не установлен, используем os.environ")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
class GiteaClient:
"""Клиент для работы с Gitea API"""
def __init__(self):
self.base_url = os.getenv('GITEA_URL', 'https://git.vyatsu.ru')
self.token = os.getenv('GITEA_TOKEN')
if not self.token:
# Пробуем альтернативные имена переменных
self.token = os.getenv('GITEA_TOKEN') or os.getenv('TOKEN')
if not self.token:
raise ValueError(
"Токен не найден!\n"
"Создайте файл .env с содержимым:\n"
"GITEA_TOKEN=ваш_токен\n"
"Или установите переменную окружения GITEA_TOKEN"
)
self.headers = {
'Authorization': f'token {self.token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
logging.info(f"✓ Инициализирован клиент для {self.base_url}")
def get_user_info(self):
"""Получение информации о пользователе"""
try:
response = requests.get(
f"{self.base_url}/api/v1/user",
headers=self.headers,
timeout=10
)
response.raise_for_status()
user = response.json()
logging.info(f"\n👤 Информация о пользователе:")
logging.info(f" Логин: {user.get('login')}")
logging.info(f" Полное имя: {user.get('full_name', 'Не указано')}")
logging.info(f" Email: {user.get('email')}")
logging.info(f" ID: {user.get('id')}")
logging.info(f" Админ: {user.get('is_admin', False)}")
return user
except requests.exceptions.RequestException as e:
logging.error(f"Ошибка получения пользователя: {e}")
return None
def create_repository(self, name, description="", private=False):
"""Создание нового репозитория"""
try:
data = {
'name': name,
'description': description,
'private': private,
'auto_init': True
}
response = requests.post(
f"{self.base_url}/api/v1/user/repos",
headers=self.headers,
json=data,
timeout=30
)
response.raise_for_status()
repo = response.json()
logging.info(f"\n✅ Репозиторий создан: {repo['html_url']}")
logging.info(f" Название: {repo['name']}")
logging.info(f" Приватный: {repo['private']}")
return repo
except requests.exceptions.RequestException as e:
logging.error(f"Ошибка создания репозитория: {e}")
if hasattr(e, 'response') and e.response:
logging.error(f"Ответ сервера: {e.response.text}")
return None
def create_issue(self, owner, repo, title, body=""):
"""Создание issue"""
try:
data = {
'title': title,
'body': body or "Создано через API PyCharm"
}
response = requests.post(
f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues",
headers=self.headers,
json=data,
timeout=30
)
response.raise_for_status()
issue = response.json()
logging.info(f"\n📝 Issue создан: {issue['html_url']}")
logging.info(f" Номер: #{issue['number']}")
logging.info(f" Заголовок: {issue['title']}")
return issue
except requests.exceptions.RequestException as e:
logging.error(f"Ошибка создания issue: {e}")
return None
def main():
"""Основная функция"""
print("=" * 50)
print("Gitea API Клиент")
print("=" * 50)
try:
client = GiteaClient()
# Получаем информацию о пользователе
user = client.get_user_info()
if not user:
return
username = user.get('login')
print("\nВыберите действие:")
print("1. Прочитать информацию")
print("2. Создать репозиторий")
print("3. Создать issue (в существующем репозитории)")
print("4. Создать репозиторий + issue (полный тест)")
choice = input("\nВаш выбор (1-4): ").strip()
if choice == '1':
client.get_user_info()
elif choice == '2':
name = input("Название репозитория: ")
desc = input("Описание: ")
private = input("Приватный? (y/n): ").lower() == 'y'
client.create_repository(name, desc, private)
elif choice == '3':
owner = input("Владелец репозитория: ")
repo = input("Название репозитория: ")
title = input("Заголовок issue: ")
body = input("Текст issue: ")
client.create_issue(owner, repo, title, body)
elif choice == '4':
repo_name = f"test-repo-{__import__('time').time()}"
print(f"\nСоздаю репозиторий {repo_name}...")
repo = client.create_repository(
name=repo_name,
description="Тестовый репозиторий из PyCharm"
)
if repo:
print("Создаю issue...")
client.create_issue(
owner=username,
repo=repo_name,
title="Тестовый issue от PyCharm",
body="Этот issue создан автоматически через Gitea API\n"
"Лабораторная работа: Работа с сетевыми соединениями"
)
except ValueError as e:
print(f"\n❌ Ошибка: {e}")
print("\nРешение:")
print("1. Создайте файл .env в корне проекта")
print("2. Добавьте в него: GITEA_TOKEN=ваш_токен")
print("3. Перезапустите программу")
except Exception as e:
print(f"\n❌ Неожиданная ошибка: {e}")
if __name__ == '__main__':
main()