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网络编程实例简析
Sep 26 Python
Python中使用装饰器和元编程实现结构体类实例
Jan 28 Python
Python利用operator模块实现对象的多级排序详解
May 09 Python
python八大排序算法速度实例对比
Dec 06 Python
解决python3中解压zip文件是文件名乱码的问题
Mar 22 Python
Python实现网站表单提交和模板
Jan 15 Python
Python eval的常见错误封装及利用原理详解
Mar 26 Python
python学习--使用QQ邮箱发送邮件代码实例
Apr 16 Python
Python 根据日志级别打印不同颜色的日志的方法示例
Aug 08 Python
计算pytorch标准化(Normalize)所需要数据集的均值和方差实例
Jan 15 Python
python如何快速拼接字符串
Oct 28 Python
Restful_framework视图组件代码实例解析
Nov 17 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
这东西价格,可以买几台TECSUN S-2000
2021/03/02 无线电
7个超级实用的PHP代码片段
2011/07/11 PHP
解析php利用正则表达式解决采集内容排版的问题
2013/06/20 PHP
PHP Global定义全局变量使用说明
2013/08/15 PHP
php根据分类合并数组的方法实例详解
2013/11/06 PHP
浅析php设计模式之数据对象映射模式
2016/03/03 PHP
深入理解PHP之OpCode原理详解
2016/06/01 PHP
LAMP环境使用Composer安装Laravel的方法
2017/03/25 PHP
php装饰者模式简单应用案例分析
2019/10/23 PHP
Git命令之分支详解
2021/03/02 PHP
xml 与javascript结合的问题解决方法
2007/03/24 Javascript
JavaScript调用堆栈及setTimeout使用方法深入剖析
2013/02/16 Javascript
详解JavaScript中undefined与null的区别
2014/03/29 Javascript
Node.js中使用Buffer编码、解码二进制数据详解
2014/08/16 Javascript
了不起的node.js读书笔记之mongodb数据库交互
2014/12/22 Javascript
常用DOM整理
2015/06/16 Javascript
浅谈javascript:两种注释,声明变量,定义函数
2016/09/29 Javascript
Json对象和字符串互相转换json数据拼接和JSON使用方式详细介绍(小结)
2016/10/25 Javascript
jQuery实现的小图列表,大图展示效果幻灯片示例
2016/10/25 Javascript
Bootstrap栅格系统的使用和理解2
2016/12/14 Javascript
AngularJS表单基本操作
2017/01/09 Javascript
Node.js 的模块知识汇总
2017/08/16 Javascript
Vue中对比scoped css和css module的区别
2018/05/17 Javascript
6种JavaScript继承方式及优缺点(小结)
2020/02/06 Javascript
vant 中van-list的用法说明
2020/11/11 Javascript
Python获取服务器信息的最简单实现方法
2015/03/05 Python
python 使用poster模块进行http方式的文件传输到服务器的方法
2019/01/15 Python
python石头剪刀布小游戏(三局两胜制)
2021/01/20 Python
Django框架安装方法图文详解
2019/11/04 Python
CSS3 实现弹幕的示例代码
2017/08/07 HTML / CSS
For Art’s Sake官网:手工制作的奢华眼镜
2018/12/15 全球购物
英国领先的酒杯和水晶玻璃器皿制造商:Dartington Crystal
2019/06/23 全球购物
Java语言程序设计测试题判断题部分
2013/01/06 面试题
《小小雨点》教学反思
2014/02/18 职场文书
单位在职证明书
2014/09/11 职场文书
Python内置数据结构列表与元组示例详解
2021/08/04 Python