1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
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
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): 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): 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)) ) return imageList
def parse_response_url(json, img_path): 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) 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
|