五、图床(github+jsDelivr)选择,图片上传并生成链接

概述

拿到淘宝商品评论图片后,需要上传到图床进行显示,找到了两个免费的图床github和微博:

图床 优点 缺点
github github提供RESTful api接口 可以使用jsDelivr加速 访问速度比较慢,上传比较慢
weibo 访问速度较快 只能一张一张上传 而且有的账号不支持外链

实现

源码文件

源码
文件 介绍
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 打造稳定快速、高效免费图床

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 最近时常在 gitee.io 上写一些 markdown 格式的文章,所以亟需获取免费的图床服务。要求是最好...
    acc8226阅读 11,640评论 4 31
  • 项目地址:https://github.com/Molunerfinn/PicGo 本人经常使用Markdown来...
    GitHub_itgoyo阅读 16,076评论 2 8
  • 1.简介 设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。 使用设计模式是为了重用代...
    穹生变阅读 1,247评论 0 1
  • 2017年突然来到,真的是十分突然。对未来有一种漫无目的的迷茫感。我对我妈妈说,现在的人吃穿不愁,可精神上的欲...
    garble阅读 1,589评论 0 1
  • 最近在研究期货,虽然结识期货已有5年了,账户一直没动,没敢动。做期货对人性的考验非常的大,因为杠杆太大,赔...
    being彬阅读 1,135评论 0 0

友情链接更多精彩内容