如何模糊Django中"自由输入"文本字段中包含的电子邮件地址

bit*_*ter 5 email django obfuscation automation textile

在我的模型中,我经常使用旨在包含大量纺织品格式输入的文本字段.我想自动模糊输入这些文本字段的任何电子邮件地址,这样当它们在模板中打印时,它们对蜘蛛是不可见的.

有一种聪明的方法吗?

更新:

根据lazerscience的答案,这是我最终使用的代码.我将文件命名为encode_mailto.py,并将其放在templatetags目录中,放在我安装到大多数django项目中的"实用程序"类型应用程序中.

import re
import random
from django.utils.safestring import mark_safe
from django import template
register = template.Library()

email_link_pat = re.compile(r'<a\s+href=("|\')?mailto:[^>]+>[^<]*</a>')
email_pat = re.compile(r'\b[-.\w]+@[-.\w]+\.[a-z]{2,4}\b')

def get_script(m):
    code_list = []
    for c in m.group(0):
        d = ord(c)
        x = random.randint(0, d)
        code_list.append("%d+%d" % (x, d-x))

    return '<script type="text/javascript">document.write(String.fromCharCode(%s))</script>' % \
        ",".join(code_list)

def encode_mailto(text):
    text = email_link_pat.sub(get_script, text)
    text = email_pat.sub(get_script, text)
    return mark_safe(text)

register.filter('encode_mailto', encode_mailto)</pre>
Run Code Online (Sandbox Code Playgroud)

然后在模板中使用它,如下所示:

{% load encode_mailto %}
{{"A bunch of text with an email address emailaddress@host.com"|encode_mailto }}
Run Code Online (Sandbox Code Playgroud)

Ber*_*ant 2

如果您只想将其用作模板标签过滤器:

import re
import random
from django.utils.safestring import mark_safe


email_link_pat = re.compile(r'<a\s+href=("|\')?mailto:[^>]+>[^<]*</a>')
email_pat = re.compile(r'\b[-.\w]+@[-.\w]+\.[a-z]{2,4}\b')

def get_script(m):
    code_list = []
    for c in m.group(0):
        d = ord(c)
        x = random.randint(0, d)
        code_list.append("%d+%d" % (x, d-x))

    return '<script type="text/javascript">document.write(String.fromCharCode(%s))</script>' % \
        ",".join(code_list)

@register.filter
def encode_mailto(text):
    text = email_link_pat.sub(get_script, text)
    text = email_pat.sub(get_script, text)
    return mark_safe(text)
Run Code Online (Sandbox Code Playgroud)

然后您可以在模板中使用它,例如:

{{ "<a href='mailto:mail@email.com'>Send Mail</a>"|encode_mailto }}
Run Code Online (Sandbox Code Playgroud)