经过metaweblog API 发布博文的时候,因为markdown中的图片路径是本地路径,将致使发布的文章图片不能正确查看。两种通用的办法是: 1 将图片发布到专用的图片服务器,而后将连接替换; 2 将图片发布到博客平台,而后将连接替换。python
这篇小文件探讨的是第二种方式。web
使用正则表达式进行查找正则表达式
def matchMarkdownLinks(post): return re.compile('!\\[.*?\\]\\((.*?)\\)').findall(post)
使用正则表达式判断是不是本地连接,若是已是网络连接,就不用进行上传操做了api
def isNetLink(link): return re.match('((http(s?))|(ftp))://.*', link)
判断图片的压缩格式,若是有必要,转换成gif格式(支持透明背景)服务器
from PIL import Image def replace_img_url(path, pictype): (name, suffix) = os.path.splitext(os.path.basename(path)) if not pictype in ["gif","jpg"]: img = Image.open(path) localfile = "%s.gif"%(name) img.save(localfile, 'gif') with open(localfile, 'rb') as f: url = client.newMediaObject({ "bits": f.read(), "name": os.path.basename(localfile), "type": "image/gif" }) os.remove(localfile) #remove local temp file return url else: with open(path, 'rb') as f: url = client.newMediaObject({ "bits": f.read(), "name": os.path.basename(path), "type": "image/" + suffix }) return url
其中的client就是上篇文章中写的metaweblog 客户端。 转换图片时,使用了PIL图片库markdown
首先使用正则获取全部连接,判断连接是不是本地连接
而后判断本地连接文件是否存在,使用 imghdr 模块猜想图片格式
最后上传本地图片,替换连接地址网络
import imghdr def fixMarkdownLink(md_file): with open(md_file, 'r', encoding="utf-8") as f: post = f.read() matchs = matchMarkdownLinks(post) print(matchs) if matchs and len(matchs) > 0: for link in matchs: if not isNetLink(link): localPath = link if not os.path.exists(localPath) or not os.path.isfile(localPath): sep = os.path.sep if (md_file.find(os.path.sep) >= 0) else ("\\" if (md_file.find("\\") >= 0) else "/") localPath = md_file[:md_file.rfind(sep)+1] + localPath if os.path.exists(localPath) and os.path.isfile(localPath): imgtype = imghdr.what(localPath) if imgtype: file_url = replace_img_url(localPath, imgtype) if file_url and file_url["url"]: post = post.replace(link, file_url["url"]) # 替换md文件中的地址 return post
未完待续,下篇继续探讨修改本地markdown文件后的自动更新方案post