我试图用相对关闭所有外部URL =“nofollow的” parametr:Django的中间件添加relnofollow所有外部链接
我写这个简单的中间件:
import re
NOFOLLOW_RE = re.compile(u'<a (?![^>]*rel=["\']nofollow[\'"])'\
u'(?![^>]*href=["\']mysite\.com[\'"])',
re.UNICODE|re.IGNORECASE)
class NofollowLinkMiddleware(object):
def process_response(self, request, response):
if ("text" in response['Content-Type']):
response.content = re.sub(NOFOLLOW_RE, u'<a rel="nofollow" ', response.content.decode('UTF8'))
return response
else:
return response
它的工作原理,但关闭内部和外部的所有链接。并且我不知道如何添加<noindex> </noindex >标记链接。
这种方法是一场噩梦。不要这样做! – 2012-07-19 14:44:14
为什么?似乎它工作得很快/ – mikhail 2012-07-21 10:36:25
原因中间件使用正则表达式处理每个响应主体,添加额外的CPU负载。随着页面内容的增长,它会吃得更多。你确定你的正则表达式会正确处理新内容吗?你应该正确地写出你的模板,避免发明新的自行车。 – 2012-07-21 19:51:06