2014-11-08 12 views
0

我想在我的django應用程序中實現一些基本的降價。目標是獲取用戶輸入並使用換行符和URL識別進行格式化。在django中使用urlize不受信任的文本

我知道我可以在模板中做到這一點:

{{ text|urlize|linebreaks }} 

有沒有辦法與不可信用戶輸入爲了做到這一點?像這樣的排序:

from django.utils.html import urlize 

def foo(request): 
    text = urlize("<script>console.log('break')</script> www.bar.com") 
    return render(request, 'index.html' {'text':text}) 

即使它呈現鏈接爲安全的,但不是字符串的其餘部分。

回答

0

的答案很可能沒有(給你的示例文本)

urlize狀態下的文檔:

如果urlize被應用到已經包含HTML標記文本,那麼就會出問題如預期。僅將此篩選器應用於純文本。

但是,如果你看來源或urlize,它實際上是非常簡單的。您可能會提取出包含URL或電子郵件的相關部分,並將其直接傳遞給urlize函數。

Django無法將字符串的一部分標記爲安全的原因在於它將整個字符串標記爲安全並返回安全的字符串對象。如果你只想要部分字符串是安全的,那麼它必須從父字符串中刪除,並自行安全(不支持只有一部分字符串需要清理,你可以清理整個字符串,也可以不清理)。

這是非常清楚在源爲SafeText

class SafeText(six.text_type, SafeData): 
    """ 
    A unicode (Python 2)/str (Python 3) subclass that has been specifically 
    marked as "safe" for HTML output purposes. 
    """ 
    def __add__(self, rhs): 
     """ 
     Concatenating a safe unicode string with another safe byte string or 
     safe unicode string is safe. Otherwise, the result is no longer safe. 
     """ 
     t = super(SafeText, self).__add__(rhs) 
     if isinstance(rhs, SafeData): 
      return SafeText(t) 
     return t 

    def _proxy_method(self, *args, **kwargs): 
     """ 
     Wrap a call to a normal unicode method up so that we return safe 
     results. The method that is being wrapped is passed in the 'method' 
     argument. 
     """ 
     method = kwargs.pop('method') 
     data = method(self, *args, **kwargs) 
     if isinstance(data, bytes): 
      return SafeBytes(data) 
     else: 
      return SafeText(data) 

    encode = curry(_proxy_method, method=six.text_type.encode) 
相關問題