python的github3模块详解

来源:互联网 发布:手机网络浏览器 编辑:程序博客网 时间:2024/06/05 12:14

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

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


来看几个例子

from github3 import logingh = login('HejunweiCoder', password='<password>')#用来提交登录的样本#gh  <GitHub [HejunweiCoder]>#gh 是一个 Github 对象userinfo = gh.user()# <User [User [HejunweiCoder:]>print userinfo.login# HejunweiCoderprint 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一次#接着我们来做写操作,写一些文件到githubdef 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"    returnstore_data("123456789")在我的github上多了一个文件,路径是data/test.data,文件内容是<pre name="code" class="python">"MTIzNDU2Nzg5"shell 里操作 echo "MTIzNDU2Nzg5" | base64 -d输出123456789



0 0
原创粉丝点击