天下脸皮共十分
我占八分

图片脚本上传最终版

import os
import time
import codecs
import re
import requests
from datetime import datetime, timedelta, timezone
import pytz


def workfile(mypath):
    for root, dirs, files in os.walk(mypath):
        for name in files:
            if name.endswith(".md"):
                filename = os.path.join(root, name)
                content = open(filename, 'r', encoding='UTF-8')
                str = content.read()
                content.close()
                matchObj = re.findall(r'(?:!\[(.*?\]\((.*?)\)))', str)
                imgObj = re.findall('(?i:src)=\"([^\"]*)\"', str)
                print(filename)
                for img in matchObj:
                    imgObj.append(img[1])
                # basic_url = 'https://pic.itstephen.cn/images/' + time.strftime("%Y/%m/%d", time.localtime()) + "/"
                basic_url = 'https://pic.itstephen.cn/images/' + getServerTimestamp() + "/"
                for pic in imgObj:
                    print(pic)
                    print(root)
                    print(filename)
                    if pic.find('https//') == -1 and pic.find('http//') == -1:
                        picPath = os.path.join(os.path.abspath(root), pic)
                        print(picPath)
                        try:
                            picupload(picPath)
                            (path, picname) = os.path.split(picPath)
                            print(picname)
                            str = str.replace(pic, basic_url + picname)
                        except:
                            pass
                replacedFile = open(filename, 'w', encoding='UTF-8')
                replacedFile.write(str)
                replacedFile.close()

def getServerTimestamp():
    td = timedelta(hours=-3)
    tz = timezone(td)
    dt = pytz.datetime.datetime.fromtimestamp(time.time(), tz)
    return dt.strftime("%Y/%m/%d")


def picupload(pic):
    url = 'https://pic.itstephen.cn/api/1/upload/?key=mykey'
    action = 'upload'
    form = {'source': open(pic, 'rb')}
    r = requests.post(url, files=form)
    print(r.content)
    # time.sleep(5)


if __name__ == '__main__':
    print('hello, world')
    path = os.path.curdir
    print(os.path.abspath("../"))
    os.listdir
    ss = 'ssasas'
    print(ss.endswith('as'))
    workfile(path)
    time.sleep(5)
赞(5) 打赏
未经允许不得转载:Stephen Young » 图片脚本上传最终版
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏