利用python脚本实现使用typora时图片自动上传到chevereto图床

前言

  • 本文参考自Hcl的个人小站
  • 本文首发于我的个人博客
  • 我是用的Typora来用markdown编写文章,使用chevereto搭建了个人图床,配合Typora的自动上传功能,参考了别人的代码,来实现粘贴图片自动上传到个人图床
  • 注意:你的typora需要是最新版

python脚本

  • 创建一个python脚本,名字随意,位置自定

    cd ~/文档/
    gedit upload.py
    
  • 复制粘贴以下代码

    #!/usr/bin/env python3
    # -*- encoding: utf-8 -*-
    # author: guiu
    # data: 2020.2.28
    
    import requests
    import json
    import mimetypes
    import argparse
    import sys
    
    APP_DESC = """
    一个上传图片到chevereto图床的命令行工具
    """
    
    print(APP_DESC)
    if len(sys.argv) == 1:
        sys.argv.append('--help')
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', type=str, nargs='+', help="", required=True)
    parser.add_argument('-c', '--config', default="./config.json", help="读取配置文件", required=True)
    args = parser.parse_args()
    
    # 从参数中获取要上传的文件列表
    img_list = args.source
    # print(img_list)
    
    def read_conf(path):
        with open(path,"r",encoding="utf-8") as f:
            confstr = f.read()
            conf = json.loads(confstr)
        return conf
    
    def up_to_chevereto(img_list):
        # 获得本地图片路径后,上传至图床并记录返回的json字段
        for img in img_list:
            # 先判断传过来的是本地路径还是远程图片地址
            if "http" == img[:4]:
                # 非本地图片的话可以考虑下载到本地再上传,但是没这个必要
                print(img)
                continue
            else:
                try:
                    res_json = upload(formatSource(img))
                    parse_response_url(res_json,img)
                except:
                    print(img+"\t上传失败")
    
    def upload(files):
        # 图床api
        # APIKey = "THERE PUT YOUR APIKEY"
        conf = read_conf(args.config)
        url = conf['url'] + "?key=" + conf['APIKEY']
        r = requests.post(url, files=files)
        return json.loads(r.text)
    
    def formatSource(filename):
        imageList = []
        mime_type = mimetypes.guess_type(filename)[0]
        imageList.append(
            ('source', (filename, open(filename, 'rb'), mime_type))
        )
        #print (imageList)
        return imageList
    
    def parse_response_url(json, img_path):
            # 从返回的json中解析字段
        if json['status_code'] != 200:
            print("{}\tweb端返回失败,可能是APIKey不对. status_code {} .".format(
                img_path, json['status_code'])
            )
        else:
            img_url = json["image"]["url"]
            print(img_url)
    
    up_to_chevereto(img_list)
    

查看你的API key

  • 到你的chevereto站点->仪表盘->设置->API

利用python脚本实现使用typora时图片自动上传到chevereto图床_第1张图片

  • 这里你可以使用默认的,也可以自定义

编写配置文件

cd ~/文档
gedit config.json
  • APIKEY:填写你的API KEY
  • url:填写你的http://你的站点域名/api/1/upload/
    • 比如我的是http://img.youwolf.cn/api/1/upload/
{
    "APIKEY": "YOUR API KEY", 
    "url": "http://your_website/api/1/upload/"
}

typora设置

  • 打开typora->文件->偏好设置->图像->上传服务设定->选择Custom Command
  • 如果需要自动上传,插入图片时选择上传图片,并勾选如图所示选项

利用python脚本实现使用typora时图片自动上传到chevereto图床_第2张图片

  • 填写以下命令,路径填你自己的

    python3 你的upload.py路径 -c 你的config.json路径 -s
    
  • 然后点击验证图片上传选项,出现以下结果表示配置正确

利用python脚本实现使用typora时图片自动上传到chevereto图床_第3张图片

你可能感兴趣的:(利用python脚本实现使用typora时图片自动上传到chevereto图床)