python代码案例:下载gitlab仓库中指定名称的文件

#!/usr/bin/env python
#coding=utf-8

import requests
import os


def run(transaction, config):
    projectPath = os.getenv("GL_PROJECT_PATH")
    res = checkProjects(projectPath)
    if res:
      return ("",0)
    else:
      exit(0)

def checkProjects(projectPath):
    # http://192.168.100.33:8888/plateform/devops.git 下的 gitlab/projects.txt  /要转换成%2F
  if 'plateform/devops' == projectPath:
    import requests
    # GitLab仓库URL
    repo_url = 'http://192.168.100.33:8888'
    # Personal Access Token (用于身份验证)
    token = 'ayeVBxaVD65892hwKtQPz47zc'
    # 项目ID或路径    
    project_id = '749'
    # 文件路径    
    file_path = 'gitlab%2Fprojects.txt'
    # 构建API请求URL
    api_url = '{}/api/v4/projects/{}/repository/files/{}/raw?ref=config'.format(repo_url,project_id,file_path)
    # 发送GET请求并下载文件    
    headers = {
    
    'PRIVATE-TOKEN': token}
    response = requests.get(api_url, headers=headers)
    print(api_url) # http://192.168.100.33:8888/api/v4/projects/749/repository/files/gitlab%2Fprojects.txt/raw?ref=config
    # 检查响应是否成功    
    if response.status_code == 200:
      # 提取文件名    
      file_name = "/opt/gitlab/embedded/service/gitlab-shell/hooks/pre-receive.d/"+file_path.split('%2F')[-1]
      # 保存文件到本地    
      with open(file_name, 'w') as file:
        file.write(response.content)
        print('文件已保存为: {}'.format(file_path.split('%2F')[-1]))
    else:
      print('下载文件失败')

猜你喜欢

转载自blog.csdn.net/a772304419/article/details/133345806