如何在Python中使用Pandas或Requests访问私有的Github Repo文件(.csv)

问题描述 投票:0回答:1

我不得不将我的公共 Github 仓库切换为私有仓库,但无法访问文件,无法使用公共 Github 仓库的访问令牌。

我可以用 curl 访问我的私有仓库的 CSV:'''curl -s https:/{token}@raw.githubusercontent.comusernamerepomasterfile.csv。

'''

然而,我想在我的python文件中访问这些信息。当repo是公开的时候,我可以简单地使用:'''url = ''''urlhttps:/raw.githubusercontent.comusernamerepomasterfile.csv。'df = pd.read_csv(url, error_bad_lines=False)

'''

现在 repo 已经被私有化了,这一点已经不适用了,而且我也找不到用 python 下载这个 CSV 而不是从终端拉取的办法。

如果我尝试:'''requests.get(https:/{token}@raw.githubusercontent.comusernamerepomasterfile.csv)'''我得到一个404响应,这与pd.read_csv()发生的事情基本相同。如果我点击原始文件,我看到一个临时标记被创建,URL是:''''https:/raw.githubusercontent.comusernamerepomasterfile.csv?token=TEMPTOKEN。'''有没有办法附加我的永久私有访问令牌,这样我就可以一直从github上调取这些数据?

python pandas git csv private
1个回答
0
投票

您是否看过 pygithub? 对于访问仓库、文件、拉取请求、历史记录等非常有用。文件是 此处. 这里有一个例子脚本,它可以打开一个拉请求,从基础分支上新建一个分支(你需要那个访问令牌,或者生成一个新的令牌!),并删除一个文件。

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)

希望能帮到你,祝你编码愉快!


0
投票

是的,你可以用Python下载CSV文件,而不是从终端拉取。要实现这一点,你可以使用GitHub API v3的 "requests "和 "io "模块协助。下面是可复制的例子。

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")
© www.soinside.com 2019 - 2024. All rights reserved.