2011-05-08 70 views
4

在我創建的網站上,我使用Python-Markdown來格式化新聞帖子。爲了避免死鏈接和HTTP內容對HTTPS頁面問題的問題,我要求編輯們將所有圖像上傳到網站,然後嵌入它們(我使用了一個我已經打補丁的降價編輯器,以允許輕鬆嵌入這些圖像使用標準markdown語法)。使用python-markdown檢查圖像網址

但是,我想在我的代碼中執行no-external-images策略。

一種方法是編寫一個正則表達式來從降價源代碼中提取圖像URL,甚至通過降價渲染器運行它,並使用DOM解析器從img標籤中提取所有src屬性。

但是,我很好奇在解析過程中是否有某種方法可以掛鉤到Python-Markdown中以提取所有圖像鏈接或執行自定義代碼(例如,如果鏈接是外部引發的異常)。

回答

6

一種方法是在一個較低的水平,以攔截<img>節點降價解析,並構建它只是後:

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 = ''' 
![Alt text](/path/to/img.jpg) 
![Alt text](http://remote.com/path/to/img.jpg) 
''' 

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 

輸出:

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> 
+0

看起來真的不錯 - 聽起來像+ 120爲代表你除非在以後再測試它時纔開始。我想我必須爲'ImagePattern'和'ImageReferencePattern'這樣做嗎? – ThiefMaster 2011-05-12 06:25:18

+0

看看這似乎很容易的事實,我可能只是完全阻止'image_link',自動添加上傳圖像的引用(帶有像'img'的一些前綴),然後更改正則表達式,以便使用此前綴定義新引用是不可能的,圖像只使用這個前綴的引用。你對此有何看法?可能會更乾淨,因爲我可以動態生成圖像URL,而不必一開始就創建它們(我需要相對/絕對URL,取決於它是否位於原子Feed或網站本身) – ThiefMaster 2011-05-12 06:30:14

+0

是的,您可以完全替換如果你願意,regexp和'ImagePattern'類本身可以拒絕/忽略'image_link'。你也需要替換'ImageReferencePattern'(爲了簡潔起見我省略),這也是正確的。我認爲你在正確的軌道上 - 根據特定於應用程序的標誌(相對/絕對,原子/站點等)自定義類行爲。 – samplebias 2011-05-12 15:33:14