概述
拿到淘宝商品评论图片后,需要上传到图床进行显示,找到了两个免费的图床github和微博:
图床 | 优点 | 缺点 |
---|---|---|
github | github提供RESTful api接口 可以使用jsDelivr加速 | 访问速度比较慢,上传比较慢 |
访问速度较快 | 只能一张一张上传 而且有的账号不支持外链 |
实现
源码文件
源码文件 | 介绍 |
---|---|
github.py | 封装github RESTful API |
main.py | 启动程序 |
settings.py | 设置 |
uploader.py | 使用github API上传图片 |
main.py
# -*-coding: utf8 -*-
import os
import settings
from github import GitHub
from uploader import Uploader
#如果图片不存在,则直接退出
if os.path.exists(settings.STORE_PATH) == False:
print('download folder not exists')
exit(1)
#创建GitHub Api
gh = GitHub(access_token=settings.TOKEN)
#切换工作目录
downloadFolder = os.getcwd() + '\\' + settings.STORE_PATH
os.chdir(downloadFolder)
#循环上传文件
for f in os.listdir(downloadFolder):
Uploader(downloadFolder,f,gh).upload()
os.chdir('..')
#重新切换工作目录
os.chdir('..')
uploader.py
# coding=utf-8
import os
import base64
import json
import settings
from github import GitHub
class Uploader(object):
def __init__(self,root,folder,gh):
self._root = root
self._folder = folder
self._gh = gh
def upload(self):
fullPath = os.path.join(self._root, self._folder)
if os.path.isdir(fullPath) != True:
return
os.chdir(fullPath)
print('start iterate '+fullPath)
if os.path.exists(fullPath+'/filelist.txt') != True:
print('filelist not exist')
txtFp = open(fullPath+'/filelist.txt','w+')
else:
txtFp = open(fullPath+'/filelist.txt','a+')
for f in os.listdir(fullPath):
fullPathFile = os.path.join(fullPath,f)
if os.path.isfile(fullPathFile) == False:
continue
ext = os.path.splitext(f)
if len(ext) < 2:
continue
if ext[1] in settings.FILTER:
print('start uploadFile')
figure = self.uploadFile(fullPathFile,f)
if len(figure) > 0:
txtFp.write(figure)
txtFp.write('\r\n')
def uploadFile(self,fullPathFile,file):
try:
with open(fullPathFile,'rb') as fp:
byte = fp.read()
base64Byte = base64.b64encode(byte).decode('utf-8')
fp.close()
print('start put contents ' + file)
hUrl = self.ghContentsPut(file,base64Byte)
if len(hUrl) > 0:
cdnUrl = settings.CDN_JSDELIVR + self._folder + '/' + file[3:]
figure = '<figure class="wp-block-image"><img src="' + cdnUrl + '" alt=""/></figure>'
return figure
return ''
except FileNotFoundError:
print('FileNotFoundError '+fullPathFile)
return ''
def ghContentsPut(self,file,base64Byte):
try:
h = self._gh.repos(settings.OWNER)(settings.REPO).contents(self._folder+'/'+file[3:]).put(message='update by hhs',content=base64Byte)
except GitHub.ApiNotFoundError:
print('ApiNotFound Error ' + self._folder+'/'+file)
return ''
except GitHub.ApiError:
print('ApiError ' + self._folder+'/'+file)
return ''
except GitHub.ApiAuthError:
print('ApiAuthError ' + self._folder+'/'+file)
return ''
except GitHub.AttributeError:
print('AttributeError ' + self._folder+'/'+file)
return ''
return h.content.download_url
参考
GitHub API v3 | GitHub Developer Guide
A simple & beautiful tool for pictures uploading built by electron-vue https://molunerfinn.com/PicGo/
A simple GitHub v3 API SDK for Python
What is a “callable”?
Github+jsDelivr+PicGo 打造稳定快速、高效免费图床
网友评论