之前的Telegraph图床失效了, 所以又从github找到一个免费的图床,
图床搭建过程建议看原文,使用R2+Page部署免费的图床【白嫖Cloudflare】 | 墓灵守护的博客 (lianglianglee.com)
作者魔改后的仓库:liangliangle/roim-picx: (github.com)
这里只讲py脚本的设置.
typora设置

Typora设置
上传服务自定义命令,
命令填入 python upload.py
不要选择 插入图片时自动转义URL 不然插入本地图片时会导致不能读取到本地图片的路径,
把py文件放在Typora的安装目录

python代码
仓库地址:loeng1995/Typora-upload (github.com)
文件结构:
使用时先在项目根目录执行 python -m pip install -r requirements.txt, 安装运行所需要的环境.
也可以自行安装requests.
代码内容:
需要更改以下参数, 第14行,第17行,和第20行代码为自己的代码.**
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| import re import sys,os import mimetypes
import requests
from time import sleep
CACHE = False
PATH= 'E'
TOKEN = '56|F1P2pVbfADCEtJjlQT1VEg5XiOqTIpBfP4xjZXNj'
URL = 'https://替换图床地址'
headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Authorization': TOKEN, 'Accept': 'application/json', 'authorization': '替换为你的authorization', 'Referer': f'{URL}' }
def upload_img(file,file_name,file_type,**kwargs): global URL url = f'{URL}/rest/upload' resp = requests.post( url, files={ "files":( file_name, file, file_type ) }, headers=headers, verify=False, **kwargs ) resp.close() if resp.status_code == 200: return resp.json() else: return 'Net Error!!' def get_sys_arg(): paths = sys.argv[1:] return paths
def parse(t): ''' 解析路径是网络地址还是本地地址
返回文件没有关闭, 则必须关闭. ''' query = re.compile(r'http[s]://') if query.match(t): ext = mimetypes.guess_extension(mimetypes.guess_type(t)) with open(f'{PATH}:/tmp.{ext}','wb') as f: resp = requests.get(t,verify=False) f.write(resp.content) f.close() global CACHE CACHE = True return f'{PATH}:/tmp.{ext}' else: return t def parse_url(json): url = json['data'][0]['url'] newUrl = f'{URL}{url}'
return newUrl
def clear_tmp(): global CACHE if CACHE: os.remove(f'{PATH}:/tmp.jpg') CACHE = False return
def get_file_name(t:str): name = t.split(r'\\')[-1] return name
if __name__ == '__main__': command = get_sys_arg() if command: for item in command:
with open(parse(item),'rb') as img: file_type = mimetypes.guess_type(item)[0] file_name = get_file_name(item) js = upload_img(img,file_name,file_type) print(parse_url(js)) sleep(1) img.close() clear_tmp() else: img = open('E:/test.png','rb') file_type = mimetypes.guess_type("E:/test.png")[0] print(file_type) js = upload_img(img,'hh.png',file_type=file_type) print(js) img.close()
|