在写PicGo_Web时,需要向Github上传图片和删除图片,这里记录下如何操作。
据我了解,能够操作Github的库有两个:
- PyGithub
- GitPython
前者通过Github Api进行操作操作,或者通过调用本地Git进行操作,各有优缺点,本次使用前者进行操作。
0x01 配置
使用PyGithub
在实例Github
类的时候需要验证github用户名和密码,或者验证Github Token,所以需要配置username, password 两个参数。
0x02 上传图片
上传文件需要指定上传远端的路径如(img/aaa.png),commit信息,上传内容,以及上传分支,其中上传内容需要读取图片内容
1 | def create_file(self, filname, content): |
2 | repo = self.__create_repo() |
3 | if isinstance(repo, str): |
4 | return 0, repo |
5 | else: |
6 | try: |
7 | repo.create_file(path=filname, message='add {}'.format(filname), content=content, branch=self.branch) #上传路径,commit信息,上传内容,上传分支 |
8 | return 1, 'https://raw.githubusercontent.com/{}/{}/{}/{}'.format(self.username, self.repository, self.branch, filname) |
9 | except Exception as e: |
10 | return 0, '添加失败' |
0x03 删除图片
删除图片时候需要现获取图片的sha
值,再进行删除
1 | def delete_file(self, filename): |
2 | repo = self.__create_repo() |
3 | if isinstance(repo, str): |
4 | return 0, repo |
5 | else: |
6 | contents = repo.get_contents(filename) #获取文件内容 |
7 | if contents: |
8 | repo.delete_file(contents.path, "remove {}".format(filename), contents.sha, branch=self.branch) |
9 | return 1, '删除成功' |
10 | else: |
11 | return 0, '删除失败' |
0x04 源代码
1 | # -*- coding: UTF-8 -*- |
2 | __author__ = 'Joynice' |
3 | |
4 | from github import Github |
5 | from config import config |
6 | |
7 | class GithubTools(Github): |
8 | |
9 | def __init__(self, username=config.GITHUB_USERNAME, password=config.GITHUB_PASSWORD, repository=config.REPOSITORIES, path=config.PATH, branch=config.BRANCH): |
10 | self.username = username |
11 | self.password = password |
12 | self.repository = repository |
13 | self.path = path |
14 | self.branch = branch |
15 | Github.__init__(self, username, password) |
16 | |
17 | def __create_repo(self): |
18 | try: |
19 | repo = self.get_repo('{}/{}'.format(self.username, self.repository)) |
20 | return repo |
21 | except: |
22 | return '连接Github API失败,请重新测试' |
23 | |
24 | def create_file(self, filname, content): |
25 | repo = self.__create_repo() |
26 | if isinstance(repo, str): |
27 | return 0, repo |
28 | else: |
29 | try: |
30 | repo.create_file(path=filname, message='add {}'.format(filname), content=content, branch=self.branch) #上传路径,commit信息,上传内容,上传分支 |
31 | return 1, 'https://raw.githubusercontent.com/{}/{}/{}/{}'.format(self.username, self.repository, self.branch, filname) |
32 | except Exception as e: |
33 | return 0, '添加失败' |
34 | |
35 | def delete_file(self, filename): |
36 | repo = self.__create_repo() |
37 | if isinstance(repo, str): |
38 | return 0, repo |
39 | else: |
40 | contents = repo.get_contents(filename) #获取文件内容 |
41 | if contents: |
42 | repo.delete_file(contents.path, "remove {}".format(filename), contents.sha, branch=self.branch) |
43 | return 1, '删除成功' |
44 | else: |
45 | return 0, '删除失败' |