前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python的github3模块详解

python的github3模块详解

作者头像
horan
修改2023-08-24 17:33:16
2070
修改2023-08-24 17:33:16
举报

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

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

来看几个例子

代码语言:javascript
复制
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
输出12345678910
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-01-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档