【问题标题】:How to Access Private Github Repo File (.csv) in Python using Pandas or Requests如何使用 Pandas 或 Requests 在 Python 中访问私有 Github Repo 文件 (.csv)
【发布时间】:2020-09-21 15:40:48
【问题描述】:

我不得不将我的公共 Github 存储库切换为私有并且无法访问文件,而不是使用我能够通过公共 Github 存储库访问的访问令牌。

我可以使用 curl 访问我的私人仓库的 CSV: ''' curl -s https://{token}@raw.githubusercontent.com/username/repo/master/file.csv

'''

但是,我想在我的 python 文件中访问这些信息。当回购公开时,我可以简单地使用: ''' 网址 = 'https://raw.githubusercontent.com/username/repo/master/file.csv' df = pd.read_csv(url, error_bad_lines=False)

'''

由于 repo 是私有的,这不再有效,我找不到解决方法来在 python 中下载此 CSV 而不是从终端中提取。

如果我尝试: ''' requests.get(https://{token}@raw.githubusercontent.com/username/repo/master/file.csv) ''' 我收到 404 响应,这与 pd.read_csv() 发生的情况基本相同。如果我单击原始文件,我会看到创建了一个临时令牌并且 URL 是: ''' https://raw.githubusercontent.com/username/repo/master/file.csv?token=TEMPTOKEN ''' 有没有办法附加我的永久私有访问令牌,以便我可以随时从 github 中提取这些数据?

【问题讨论】:

    标签: python pandas git csv private


    【解决方案1】:

    是的,您可以在 Python 中下载 CSV 文件,而不是从终端拉取。为此,您可以使用带有“请求”和“io”模块帮助的 GitHub API v3。下面的可重现示例。

    import numpy as np
    import pandas as pd
    import requests
    from io import StringIO
    
    # Create CSV file
    df = pd.DataFrame(np.random.randint(2,size=10_000).reshape(1_000,10))
    df.to_csv('filename.csv') 
    
    # -> now upload file to private github repo
    
    # define parameters for a request
    token = 'paste-there-your-personal-access-token' 
    owner = 'repository-owner-name'
    repo = 'repository-name-where-data-is-stored'
    path = 'filename.csv'
    
    # send a request
    r = requests.get(
        'https://api.github.com/repos/{owner}/{repo}/contents/{path}'.format(
        owner=owner, repo=repo, path=path),
        headers={
            'accept': 'application/vnd.github.v3.raw',
            'authorization': 'token {}'.format(token)
                }
        )
    
    # convert string to StringIO object
    string_io_obj = StringIO(r.text)
    
    # Load data to df
    df = pd.read_csv(string_io_obj, sep=",", index_col=0)
    
    # optionally write df to CSV
    df.to_csv("file_name_02.csv")
    

    【讨论】:

      【解决方案2】:

      这最终对我有用——如果有人遇到同样的问题,就把它留在这里。感谢您的帮助!

          import json, requests, urllib, io
      
          user='my_github_username'
          pao='my_pao'
      
          github_session = requests.Session()
          github_session.auth = (user, pao)
      
          # providing raw url to download csv from github
          csv_url = 'https://raw.githubusercontent.com/user/repo/master/csv_name.csv'
      
          download = github_session.get(csv_url).content
          downloaded_csv = pandas.read_csv(io.StringIO(download.decode('utf-8')), error_bad_lines=False)
      

      【讨论】:

      • 嘿,所以我正在使用一个类似的私有 repo (.csv) 文件,并且想知道除了阅读它之外,我还有什么方法可以编辑托管在 github 上的文件。直觉上我认为我应该能够编辑数据,因为我可以读取数据,但我无法找到解决方案。
      • 您可以对文件进行编辑,但您必须提交更改并将更改推送到存储库。因为你可以只使用 git 命令
      【解决方案3】:

      你看过pygithub吗?对于访问存储库、文件、拉取请求、历史记录等非常有用。文档是 here。这是一个示例脚本,它打开一个拉取请求、一个从基础分支创建的新分支(您将需要该访问令牌,或者生成一个新的!),并删除一个文件:

      from github import Github
      my_reviewers = ['usernames', 'of_reviewers']
      gh = Github("<token string>")
      repo_name = '<my_org>/<my_repo>'
      repo = gh.get_repo(repo_name)
      default_branch_name = repo.default_branch
      base = repo.get_branch(default_branch_name)
      new_branch_name = "my_new_branchname"
      new_branch = repo.create_git_ref(ref=f'refs/heads/{new_branch_name}',sha=base.commit.sha)
      contents = repo.get_contents("some_script_in_repo.sh", ref=new_branch_name)
      repo.delete_file(contents.path, "commit message", contents.sha, branch=new_branch_name)
      pr = repo.create_pull(
          title="PR to Remove some_script_in_repo.sh",
          body="This is the text in the main body of your pull request",
          head=new_branch_name,
          base=default_branch_name,
      )
      pr.create_review_request(reviewers=my_reviewers)
      

      希望对您有所帮助,祝您编码愉快!

      【讨论】:

        【解决方案4】:

        这种方式对我很有用:

            def _github(url: str, mode: str = "private"):
                url = url.replace("/blob/", "/")
                url = url.replace("/raw/", "/")
                url = url.replace("github.com/", "raw.githubusercontent.com/")
        
                if mode == "public":
                    return requests.get(url)
                else:
                    token = os.getenv('GITHUB_TOKEN', '...')
                    headers = {
                        'Authorization': f'token {token}',
                        'Accept': 'application/vnd.github.v3.raw'}
                    return requests.get(url, headers=headers)
        

        【讨论】:

        • 但是如何使用这个功能呢?请详细说明。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        • 2019-07-01
        • 1970-01-01
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 2019-08-09
        相关资源
        最近更新 更多