我在 Mozilla 的大部分时间都花在了追赶 MDN 团队其他成员的 Python 方面。 新的 MDN 后端,代号为 Kuma,完全基于 Django,学习起来很有趣。 我最近的 python 冒险一直专注于提高 MDN 的 SEO 分数,这项任务包括告诉谷歌不要索引给定的页面。 在这样做的过程中,我创建了我的第一个视图装饰器:一个发送响应头的装饰器,它可以防止机器人索引给定的页面。
蟒蛇
第一步是导入装饰器依赖项:
from functools import wraps
下一步是创建装饰器定义:
def prevent_indexing(view_func):
"""Decorator to prevent a page from being indexable by robots"""
@wraps(view_func)
def _added_header(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
response['X-Robots-Tag'] = 'noindex'
return response
return _added_header
处理原始视图,以便接收响应; 简单的在响应中添加一个 X-Robots-Tag 的 key,value 设置为 noindex,装饰器就完成了!
要使用装饰器,只需将其添加到给定视图中:
@login_required
@prevent_indexing
def new_document(request):
""" Does whatever 'new_document' should do; page should not be indexed """
瞧——将发送 X-Robots-Tag 标头,以便机器人不会索引页面! 装饰器允许为任何视图加载附加功能,并且易于重用; 我很高兴将它们添加到我的武器库中!