lab3token/api copy.py

95 lines
3.9 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.

import os
from dotenv import load_dotenv
import requests
# Загрузка переменных окружения из файла .env
load_dotenv()
# Получение токена из переменной окружения
TOKEN = os.getenv("GITEA_TOKEN2")
if not TOKEN:
raise ValueError("Токен не найден. Убедитесь, что он добавлен в файл .env.")
# Базовые заголовки для авторизации
headers = {"Authorization": f"token {TOKEN}"}
# Данные пользователя
owner = "stud178857" # Замените на ваш логин в Gitea
repo_name = "test-repo-student" # Уникальное имя репозитория (можно изменить)
# URL для API
base_url = "https://git.vyatsu.ru/api/v1"
# --- Функция 1: Создание репозитория ---
def create_repository():
url = f"{base_url}/user/repos"
data = {
"name": repo_name,
"description": "Это тестовый репозиторий, созданный через API",
"private": False, # Публичный репозиторий
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
print("Репозиторий успешно создан!")
return response.json()
else:
print(f"Ошибка при создании репозитория: {response.status_code}")
print(response.text)
return None
# --- Функция 2: Создание Issue ---
def create_issue(repo_name):
url = f"{base_url}/repos/{owner}/{repo_name}/issues"
data = {
"title": "Тестовый Issue", # Заголовок Issue
"body": "Это тестовый Issue, созданный через API", # Описание Issue
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
print("Issue успешно создан!")
return response.json()
else:
print(f"Ошибка при создании Issue: {response.status_code}")
print(response.text)
return None
# --- Функция 3: Создание комментария к Issue ---
def create_comment(repo_name, issue_index):
url = f"{base_url}/repos/{owner}/{repo_name}/issues/{issue_index}/comments"
data = {
"body": "Это тестовый комментарий, созданный через API", # Текст комментария
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
print("Комментарий успешно создан!")
return response.json()
else:
print(f"Ошибка при создании комментария: {response.status_code}")
print(response.text)
return None
# --- Основная логика ---
if __name__ == "__main__":
try:
# 1. Создаем репозиторий
repo_response = create_repository()
if not repo_response:
raise Exception("Не удалось создать репозиторий.")
# 2. Создаем Issue в новом репозитории
issue_response = create_issue(repo_name)
if not issue_response:
raise Exception("Не удалось создать Issue.")
# Извлекаем номер Issue
issue_index = issue_response.get("number")
if not issue_index:
raise Exception("Не удалось получить номер Issue.")
# 3. Добавляем комментарий к Issue
comment_response = create_comment(repo_name, issue_index)
if not comment_response:
raise Exception("Не удалось создать комментарий.")
except Exception as e:
print(f"Произошла ошибка: {e}")