Django Sitemap 站点地图的实现方法


Posted in Python onApril 29, 2019

Django 中自带了 sitemap框架,用来生成 xml 文件

Sitemap(站点地图)是通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。 白话文就是:一个写了你网站的所有url的xml文件,告诉搜索引擎,请及时收录我的这些地址。

sitemap 很重要,可以用来通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。

开启sitemap功能的步骤

settings.py 文件中 django.contrib.sitemaps 和 django.contrib.sites 要在 INSTALL_APPS 中

INSTALLED_APPS = (
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'django.contrib.sites',
  'django.contrib.sitemaps',
  'django.contrib.redirects',
   
  #####
  #othther apps
  #####
)

Django 1.7 及以前版本:

TEMPLATE_LOADERS 中要加入 'django.template.loaders.app_directories.Loader',像这样:

TEMPLATE_LOADERS = (
  'django.template.loaders.filesystem.Loader',
  'django.template.loaders.app_directories.Loader',
 )

Django 1.8 及以上版本新加入了 TEMPLATES 设置,其中 APP_DIRS 要为 True,比如:

# NOTICE: code for Django 1.8, not work on Django 1.7 and below
TEMPLATES = [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
      os.path.join(BASE_DIR,'templates').replace('\\', '/'),
    ],
    'APP_DIRS': True,
  },
]

然后在 urls.py 中如下配置:

from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
 
from blog.models import Entry
 
 
sitemaps = {
  'blog': GenericSitemap({'queryset': Entry.objects.all(), 'date_field': 'pub_date'}, priority=0.6),
  # 如果还要加其它的可以模仿上面的
}
 
urlpatterns = [
  # some generic view using info_dict
  # ...
 
  # the sitemap
  url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
    name='django.contrib.sitemaps.views.sitemap'),
]

但是这样生成的 sitemap,如果网站内容太多就很慢,很耗费资源,可以采用分页的功能:

from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
 
from blog.models import Entry
 
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page
 
 
sitemaps = {
  'blog': GenericSitemap({'queryset': Entry.objects.all(), 'date_field': 'pub_date'}, priority=0.6),
  # 如果还要加其它的可以模仿上面的
}
 
urlpatterns = [
  url(r'^sitemap\.xml$',
    cache_page(86400)(sitemaps_views.index),
    {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
  url(r'^sitemap-(?P<section>.+)\.xml$',
    cache_page(86400)(sitemaps_views.sitemap),
    {'sitemaps': sitemaps}, name='sitemaps'),
]

这样就可以看到类似如下的 sitemap,如果本地测试访问 http://localhost:8000/sitemap.xml

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=2</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=3</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=4</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=5</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=6</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=7</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=8</loc></sitemap>
<sitemap><loc>http://www.ziqiangxuetang.com/sitemap-tutorials.xml?p=9</loc></sitemap>
</sitemapindex>

查看了下分页是实现了,但是全部显示成了 ?p=页面数,而且在百度站长平台上测试,发现这样的sitemap百度报错,于是看了下 Django的源代码:

在这里 https://github.com/django/django/blob/1.7.7/django/contrib/sitemaps/views.py

于是对源代码作了修改,变成了本站的sitemap的样子,比 ?p=2 这样更优雅

引入 下面这个 比如是 sitemap_views.py

import warnings
from functools import wraps
 
from django.contrib.sites.models import get_current_site
from django.core import urlresolvers
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.http import Http404
from django.template.response import TemplateResponse
from django.utils import six
 
def x_robots_tag(func):
  @wraps(func)
  def inner(request, *args, **kwargs):
    response = func(request, *args, **kwargs)
    response['X-Robots-Tag'] = 'noindex, noodp, noarchive'
    return response
  return inner
 
@x_robots_tag
def index(request, sitemaps,
     template_name='sitemap_index.xml', content_type='application/xml',
     sitemap_url_name='django.contrib.sitemaps.views.sitemap',
     mimetype=None):
 
  if mimetype:
    warnings.warn("The mimetype keyword argument is deprecated, use "
      "content_type instead", DeprecationWarning, stacklevel=2)
    content_type = mimetype
 
  req_protocol = 'https' if request.is_secure() else 'http'
  req_site = get_current_site(request)
 
  sites = []
  for section, site in sitemaps.items():
    if callable(site):
      site = site()
    protocol = req_protocol if site.protocol is None else site.protocol
    for page in range(1, site.paginator.num_pages + 1):
      sitemap_url = urlresolvers.reverse(
          sitemap_url_name, kwargs={'section': section, 'page': page})
      absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
      sites.append(absolute_url)
 
  return TemplateResponse(request, template_name, {'sitemaps': sites},
              content_type=content_type)
 
@x_robots_tag
def sitemap(request, sitemaps, section=None, page=1,
      template_name='sitemap.xml', content_type='application/xml',
      mimetype=None):
 
  if mimetype:
    warnings.warn("The mimetype keyword argument is deprecated, use "
      "content_type instead", DeprecationWarning, stacklevel=2)
    content_type = mimetype
 
  req_protocol = 'https' if request.is_secure() else 'http'
  req_site = get_current_site(request)
 
  if section is not None:
    if section not in sitemaps:
      raise Http404("No sitemap available for section: %r" % section)
    maps = [sitemaps[section]]
  else:
    maps = list(six.itervalues(sitemaps))
     
  urls = []
  for site in maps:
    try:
      if callable(site):
        site = site()
      urls.extend(site.get_urls(page=page, site=req_site,
                   protocol=req_protocol))
    except EmptyPage:
      raise Http404("Page %s empty" % page)
    except PageNotAnInteger:
      raise Http404("No page '%s'" % page)
  return TemplateResponse(request, template_name, {'urlset': urls},
              content_type=content_type)

如果还是不懂,可以下载附件查看:zqxt_sitemap.zip

更多参考:

官方文档:https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的gevent框架的入门教程
Apr 29 Python
玩转python爬虫之正则表达式
Feb 17 Python
Phantomjs抓取渲染JS后的网页(Python代码)
May 13 Python
Windows下Python3.6安装第三方模块的方法
Nov 22 Python
Python jieba库用法及实例解析
Nov 04 Python
Python3 集合set入门基础
Feb 10 Python
150行Python代码实现带界面的数独游戏
Apr 04 Python
解决Pycharm 中遇到Unresolved reference 'sklearn'的问题
Jul 13 Python
python的链表基础知识点
Sep 13 Python
PyCharm Community安装与配置的详细教程
Nov 24 Python
python实现ping命令小程序
Dec 28 Python
python中pdb模块实例用法
Jan 15 Python
python中报错&quot;json.decoder.JSONDecodeError: Expecting value:&quot;的解决
Apr 29 #Python
python实现微信定时每天和女友发送消息
Apr 29 #Python
Python3.5常见内置方法参数用法实例详解
Apr 29 #Python
python微信撤回监测代码
Apr 29 #Python
Python3.5 Json与pickle实现数据序列化与反序列化操作示例
Apr 29 #Python
详解Python中的内建函数,可迭代对象,迭代器
Apr 29 #Python
python抓取需要扫微信登陆页面
Apr 29 #Python
You might like
10个实用的PHP代码片段
2011/09/02 PHP
PHP生成不重复标识符的方法
2014/11/21 PHP
Thinkphp3.2.3整合phpqrcode生成带logo的二维码
2016/07/21 PHP
php实现的统计字数函数定义与使用示例
2017/07/26 PHP
PHP Socket网络操作类定义与用法示例
2017/08/30 PHP
Thinkphp5 微信公众号token验证不成功的原因及解决方法
2017/11/12 PHP
PHP simplexml_import_dom()函数讲解
2019/02/03 PHP
document.compatMode介绍
2009/05/21 Javascript
Javascript表达式中连续的 &amp;&amp; 和 || 之赋值区别
2010/10/17 Javascript
JavaScript跨域方法汇总
2014/10/16 Javascript
jQuery对象与DOM对象之间的相互转换
2015/03/03 Javascript
PHP+MySQL+jQuery随意拖动层并即时保存拖动位置实例讲解
2015/10/09 Javascript
Jquery时间轴特效(三种不同类型)
2015/11/02 Javascript
关于Jquery中的bind(),on()绑定事件方式总结
2016/10/26 Javascript
Jquery-data的三种用法
2017/04/18 jQuery
jquery图片放大镜效果
2017/06/23 jQuery
jQuery validata插件实现方法
2017/06/25 jQuery
JS中的JSON对象的定义和取值实现代码
2018/05/09 Javascript
Javascript获取某个月的天数
2018/05/30 Javascript
小程序中canvas的drawImage方法参数使用详解
2019/07/04 Javascript
微信小程序实现Swiper轮播图效果
2019/11/22 Javascript
Vue常用传值方式、父传子、子传父及非父子实例分析
2020/02/24 Javascript
原生js实现ajax请求和JSONP跨域请求操作示例
2020/03/14 Javascript
js+cavans实现图片滑块验证
2020/09/29 Javascript
[51:53]完美世界DOTA2联赛决赛日 Inki vs LBZS 第二场 11.08
2020/11/10 DOTA
Python 字典dict使用介绍
2014/11/30 Python
详解Python中break语句的用法
2015/05/14 Python
python字符串str和字节数组相互转化方法
2017/03/18 Python
使用Python实现一个栈判断括号是否平衡
2018/08/23 Python
python 搭建简单的http server,可直接post文件的实例
2019/01/03 Python
PyCharm安装Markdown插件的两种方法
2019/06/24 Python
python getpass模块用法及实例详解
2019/10/07 Python
俄罗斯最大的消费电子连锁零售商:Mvideo
2017/06/25 全球购物
采购部2015年度工作总结
2015/07/24 职场文书
2019学校请假条格式及范文
2019/06/25 职场文书
如何利用python和DOS获取wifi密码
2021/03/31 Python