在我正在创建的网站上,我正在使用Python-Markdown格式化新闻帖子.为了避免死链接和HTTP-content-on-HTTPS-page问题的问题,我要求编辑将所有图像上传到网站然后嵌入它们(我使用的是降价编辑器,我已修补它以便于嵌入那些使用标准降价语法的图像).
但是,我想在我的代码中强制执行无外部映像策略.
一种方法是编写正则表达式从markdown源代码中提取图像URL,或者甚至通过markdown渲染器运行它,并使用DOM解析器src从img标记中提取所有属性.
但是,我很好奇是否有一些方法可以在解析过程中连接到Python-Markdown以提取所有图像链接或执行自定义代码(例如,如果链接是外部的,则引发异常).
一种方法是<img>在Markdown解析并构造它之后拦截较低级别的节点:
import re
from markdown import Markdown
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE
RE_REMOTEIMG = re.compile('^(http|https):.+')
class CheckImagePattern(ImagePattern):
def handleMatch(self, m):
node = ImagePattern.handleMatch(self, m)
# check 'src' to ensure it is local
src = node.attrib.get('src')
if src and RE_REMOTEIMG.match(src):
print 'ILLEGAL:', m.group(9)
# or alternately you could raise an error immediately
# raise ValueError("illegal remote url: %s" % m.group(9))
return node
DATA = '''


'''
mk = Markdown()
# patch in the customized image pattern matcher with url checking
mk.inlinePatterns['image_link'] = CheckImagePattern(IMAGE_LINK_RE, mk)
result = mk.convert(DATA)
print result
Run Code Online (Sandbox Code Playgroud)
输出:
ILLEGAL: http://remote.com/path/to/img.jpg
<p><img alt="Alt text" src="/path/to/img.jpg" />
<img alt="Alt text" src="http://remote.com/path/to/img.jpg" /></p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2189 次 |
| 最近记录: |