python的github3模块详解

python的github3的模块,提供了程序里实现与github交互的功能。附上官方文档:

https://github3py.readthedocs.org/en/master/


来看几个例子

from github3 import login

gh = login('HejunweiCoder', password='<password>')
#用来提交登录的样本
#gh  <GitHub [HejunweiCoder]>
#gh 是一个 Github 对象
userinfo = gh.user()
# <User [User [HejunweiCoder:]>
print userinfo.login
# HejunweiCoder
print userinfo.followers
# 0
# 新鸟一只,大家多多关照


repo=gh.repository("HejunweiCoder","RepositoryName")
#第一个参数是账号名称(也可以是别人的,看你怎么用),第二个是你的仓库名称(我用的是public,private的仓库请自行参考)
#返回一个Repository对象,就是在github上的仓库
branch=repo.branch("master")
#返回一个branch对象,参数是branch的名称,得到那个分支,不着急,再往后看

branch.links
#它会返回:
{u'self': u'https://api.github.com/repos/HejunweiCoder/ControlCenter/branches/master',
u'html': u'https://github.com/HejunweiCoder/ControlCenter/tree/master'}

tree=branch.commit.commit.tree.recurse()
type(atree)
<class 'github3.git.Tree'>
#这是我们之后用来遍历的方法


#我们把连接过程写成一个函数,在之后去调用
def connect_to_github():
    gh=login(username="<username>",password="<password>")
    repo=gh.repository("<username>","<repository>")
    branch=repo.branch("master")
    #将参数设置github名称密码和仓库名,我们之后将操作得到的这三个对象
    return gh,repo,branch


#我们试着来看一些文件是否在github存在,写另一个函数
def get_file_contents(filepath):
    gh,repo,branch=connect_to_github()
    tree=branch.commit.commit.tree.recurse()

    for filename in tree.tree:
        #tree.tree是一个list,里边包含了在这个仓库下所有的文件,值是Hash对象
        #而这个对象包含了_json_data这个字典,和type,size,url,path等元素

        #我们去比对这些文件里有没有和传入的那个文件名一致的,filename.path的值像是u'.idea'这样的字符串
        if filepath in filename.path:
            print "[*] Found file %s "% filepath
            blob=repo.blob(filename._json_data["sha"])
            return blob.content

#我们来看一下blob这个变量,bolob.content.decode是这样的
    #可以得到json的结构
[
  {
    "module" : "dirlister"
  },
  {
    "module" : "environment"
  }
]
    #这是我跑到的某个json文件的内容
    #这个是base64加密的
    #输出像这样 WwogIHsKICAgICJtb2R1bGUiIDogImRpcmxpc3RlciIKICB9LAogIHsKICAg*****
    #用base64.b64decode解开后和前面的一样,所以我们传回的值需要decode一次



#接着我们来做写操作,写一些文件到github
def store_data(data):

    gh,repo,branch=connect_to_github()
    remote_path = "data/test.data"
    repo.create_file(remote_path,"Commite message",base64.b64encode(data))
    #注意文件名不能在github上重复
    #为了安全起见我对上传的文件内容进行来base64加密
    print "upload success"
    return


store_data("123456789")

在我的github上多了一个文件,路径是data/test.data,文件内容是<pre name="code" class="python">"MTIzNDU2Nzg5"
shell 里操作 echo "MTIzNDU2Nzg5" | base64 -d
输出123456789

 



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值