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 字符串操作实现代码(截取/替换/查找/分割)
Jun 08 Python
Python中的闭包总结
Sep 18 Python
Python 正则表达式(转义问题)
Dec 15 Python
Python中splitlines()方法的使用简介
May 20 Python
python在Windows下安装setuptools(easy_install工具)步骤详解
Jul 01 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
Python魔法方法功能与用法简介
Apr 04 Python
PyTorch使用cpu加载模型运算方式
Jan 13 Python
python中with用法讲解
Feb 07 Python
python 实现一个图形界面的汇率计算器
Nov 09 Python
PyTorch中clone()、detach()及相关扩展详解
Dec 09 Python
python实现经纬度采样的示例代码
Dec 10 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
PHP 读取大文件的X行到Y行内容的实现代码
2013/06/24 PHP
phpMyAdmin自动登录和取消自动登录的配置方法
2014/05/12 PHP
PHP使用curl函数发送Post请求的注意事项
2016/11/26 PHP
PHP获取当前日期及本周一是几月几号的方法
2017/03/28 PHP
PHP实现将几张照片拼接到一起的合成图片功能【便于整体打印输出】
2017/11/14 PHP
js 数据类型转换总结笔记
2011/01/17 Javascript
javascript写的简单的计算器,内容很多,方法实用,推荐
2011/12/29 Javascript
基于IE下ul li 互相嵌套时的bug,排查,解决过程以及心得介绍
2013/05/07 Javascript
jquery跟js初始化加载的多种方法及区别介绍
2014/04/02 Javascript
两种方法基于jQuery实现IE浏览器兼容placeholder效果
2014/10/14 Javascript
jquery插件corner实现圆角边框的方法
2015/03/09 Javascript
4种JavaScript实现简单tab选项卡切换的方法
2016/01/06 Javascript
JS设置cookie、读取cookie
2016/02/24 Javascript
jquery uploadify隐藏上传进度的实现方法
2017/02/06 Javascript
微信小程序使用checkbox显示多项选择框功能【附源码下载】
2017/12/11 Javascript
浅析node应用的timing-attack安全漏洞
2018/02/28 Javascript
详解vue项目打包后通过百度的BAE发布到网上的流程
2018/03/05 Javascript
Vue2.0学习系列之项目上线的方法步骤(图文)
2018/09/25 Javascript
微信小程序使用component自定义toast弹窗效果
2018/11/27 Javascript
Element ui 下拉多选时新增一个选择所有的选项
2019/08/21 Javascript
转换layUI的数据表格中的日期格式方法
2019/09/19 Javascript
[01:16:50]DOTA2-DPC中国联赛 正赛 Phoenix vs CDEC BO3 第一场 3月7日
2021/03/11 DOTA
Python文件操作之合并文本文件内容示例代码
2017/09/19 Python
Django 静态文件配置过程详解
2019/07/23 Python
解决jupyter notebook打不开无反应 浏览器未启动的问题
2020/04/10 Python
keras中模型训练class_weight,sample_weight区别说明
2020/05/23 Python
PyCharm中关于安装第三方包的三个建议
2020/09/17 Python
详解HTML5中的Communication API基本使用方法
2016/01/29 HTML / CSS
Sam’s Club山姆会员商店:沃尔玛旗下高端会员制商店
2017/01/16 全球购物
英国的屈臣氏:Boots博姿
2017/12/23 全球购物
英国知名美妆护肤在线商城:Zest Beauty
2018/04/24 全球购物
2014幼儿教师个人工作总结
2014/12/03 职场文书
2015年秘书个人工作总结
2015/04/25 职场文书
垂直极限观后感
2015/06/08 职场文书
运动会开幕式致辞
2015/07/29 职场文书
2015年乡镇组织委员工作总结
2015/10/23 职场文书