Python을 사용하여 Github 리포지토리 데이터를 검색하는 방법

Patricia Arquette
풀어 주다: 2024-09-29 06:12:30
원래의
189명이 탐색했습니다.

How to retrieve Github Repository Data using Python

귀하의 조직에 Github 저장소가 너무 많아서 보고, 대시보드 또는 감사 목적으로 각 저장소의 내용을 쉽게 요약하고 기록할 수 있는 방법이 필요합니까? Github API를 사용하여 바로 그 작업을 수행하는 빠른 스크립트는 다음과 같습니다.

기능:

  1. get_repo_info(소유자, 저장소):

    • GitHub 저장소 소유자의 사용자 이름(소유자)과 저장소 이름(repo)을 가져옵니다.
    • GitHub의 API에 요청을 보내 저장소 정보를 가져옵니다.
    • 성공하면 저장소 정보를 JSON 객체로 반환하고, 오류가 있으면 None을 반환합니다.
  2. get_collaborators(collaborators_url):

    • 저장소의 공동작업자 목록에 대한 URL을 가져옵니다.
    • 공동작업자 목록을 가져오기 위한 요청을 보냅니다.
    • 공동작업자 사용자 이름 목록을 반환하거나, 오류가 발생하면 빈 목록을 반환합니다.
  3. get_언어(언어_url):

    • 저장소의 언어 데이터에 대한 URL을 가져옵니다.
    • 저장소에서 사용되는 프로그래밍 언어를 검색하라는 요청을 보냅니다.
    • 언어 목록을 반환하거나 오류가 있는 경우 빈 목록을 반환합니다.
  4. get_open_issues(소유자, 저장소):

    • 저장소 소유자의 사용자 이름(owner)과 저장소 이름(repo)을 가져옵니다.
    • 저장소에 있는 미해결 문제 목록을 검색하라는 요청을 보냅니다.
    • 미해결 이슈를 JSON 형식으로 반환하거나, 문제가 있는 경우 오류 메시지를 출력합니다.
  5. get_repo_data(repo_url):

    • 저장소 URL을 가져와 구문 분석하여 소유자 및 저장소 값을 가져온 다음 다른 함수를 호출하여 저장소에 대한 다양한 정보를 수집합니다.
    • 이름, 소유자, 가시성, 공동작업자, 언어, 공개 이슈, 마지막 활동을 포함한 저장소 정보를 컴파일하여 구조화된 형식(사전)으로 반환합니다.
import json
import requests
from pymongo import MongoClient

# MongoDB setup (replace with your actual connection details)
client = MongoClient("mongodb://localhost:27017/")
db = client["github_repos"]  # Database name
collection = db["repos"]     # Collection name

def get_repo_info(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}"
    headers = {"Accept": "application/vnd.github+json"}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

def get_collaborators(collaborators_url):
    response = requests.get(collaborators_url)
    if response.status_code == 200:
        return [collaborator["login"] for collaborator in response.json()]
    else:
        return []

def get_languages(languages_url):
    response = requests.get(languages_url)
    if response.status_code == 200:
        return list(response.json().keys())
    else:
        return []

def get_open_issues(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}/issues?state=open"
    headers = {"Accept": "application/vnd.github+json"}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return []

def get_repo_data(repo_url):
    owner, repo = repo_url.split("/")[-2:]
    repo_info = get_repo_info(owner, repo)

    if repo_info:
        data = {
            "Github URL": repo_url,
            "Project name": repo_info["name"],
            "Project owner": repo_info["owner"]["login"],
            "List users with access": get_collaborators(repo_info["collaborators_url"].split("{")[0]),  # remove template part of URL
            "Programming languages used": get_languages(repo_info["languages_url"]),
            "Security/visibility level": repo_info["visibility"],
            "Summary": repo_info["description"],
            "Last maintained": repo_info["pushed_at"],
            "Last release": repo_info["default_branch"],
            "Open issues": get_open_issues(owner, repo),
        }

        # Insert the data into MongoDB
        collection.insert_one(data)
        print("Data inserted into MongoDB successfully.")

        return data
    else:
        return None

# Example usage
repo_url = "https://github.com/URL"
repo_data = get_repo_data(repo_url)

if repo_data:
    print(json.dumps(repo_data, indent=4))
로그인 후 복사

위 내용은 Python을 사용하여 Github 리포지토리 데이터를 검색하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!