在Django中使用Sitemap的方法讲解


Posted in Python onJuly 22, 2015

sitemap 是你服务器上的一个XML文件,它告诉搜索引擎你的页面的更新频率和某些页面相对于其它页面的重要性。 这个信息会帮助搜索引擎索引你的网站。

例如,这是 Django 网站(http://www.djangoproject.com/sitemap.xml)sitemap的一部分:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc>http://www.djangoproject.com/documentation/</loc>
  <changefreq>weekly</changefreq>
  <priority>0.5</priority>
 </url>
 <url>
  <loc>http://www.djangoproject.com/documentation/0_90/</loc>
  <changefreq>never</changefreq>
  <priority>0.1</priority>
 </url>
 ...
</urlset>

需要了解更多有关 sitemaps 的信息, 请参见 http://www.sitemaps.org/.

Django sitemap 框架允许你用 Python 代码来表述这些信息,从而自动创建这个XML文件。 要创建一个站点地图,你只需要写一个`` Sitemap`` 类,并且在URLconf中指向它。
安装

要安装 sitemap 应用程序, 按下面的步骤进行:

  •     将 'django.contrib.sitemaps' 添加到您的 INSTALLED_APPS 设置中.
  •     确保 'django.template.loaders.app_directories.load_template_source' 在您的 TEMPLATE_LOADERS 设置中。 默认情况下它在那里, 所以, 如果你已经改变了那个设置的话, 只需要改回来即可。
  •     确定您已经安装了 sites 框架.

Note

sitemap 应用程序没有安装任何数据库表. 它需要加入到 INSTALLED_APPS 中的唯一原因是: 这样 load_template_source 模板加载器可以找到默认的模板. The only reason it needs to go into INSTALLED_APPS is so the load_template_source template loader can find the default templates.
Initialization

要在您的Django站点中激活sitemap生成, 请在您的 URLconf 中添加这一行:

(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})

This line tells Django to build a sitemap when a client accesses /sitemap.xml . Note that the dot character in sitemap.xml is escaped with a backslash, because dots have a special meaning in regular expressions.

sitemap文件的名字无关紧要,但是它在服务器上的位置却很重要。 搜索引擎只索引你的sitemap中当前URL级别及其以下级别的链接。 用一个实例来说,如果 sitemap.xml 位于你的根目录,那么它将引用任何的URL。 然而,如果你的sitemap位于 /content/sitemap.xml ,那么它只引用以 /content/ 打头的URL。

sitemap视图需要一个额外的必须的参数: {'sitemaps': sitemaps} . sitemaps should be a dictionary that maps a short section label (e.g., blog or news ) to its Sitemap class (e.g., BlogSitemap or NewsSitemap ). It may also map to an instance of a Sitemap class (e.g., BlogSitemap(some_var) ).
Sitemap 类

Sitemap 类展示了一个进入地图站点简单的Python类片断.例如,一个 Sitemap 类能展现所有日志入口,而另外一个能够调度所有的日历事件。 For example, one Sitemap class could represent all the entries of your weblog, while another could represent all of the events in your events calendar.

在最简单的例子中,所有部分可以全部包含在一个 sitemap.xml 中,也可以使用框架来产生一个站点地图,为每一个独立的部分产生一个单独的站点文件。

Sitemap 类必须是 django.contrib.sitemaps.Sitemap 的子类. 他们可以存在于您的代码树的任何地方。

例如假设你有一个blog系统,有一个 Entry 的model,并且你希望你的站点地图包含所有连到你的blog入口的超链接。 你的 Sitemap 类很可能是这样的:

from django.contrib.sitemaps import Sitemap
from mysite.blog.models import Entry

class BlogSitemap(Sitemap):
  changefreq = "never"
  priority = 0.5

  def items(self):
    return Entry.objects.filter(is_draft=False)

  def lastmod(self, obj):
    return obj.pub_date

声明一个 Sitemap 和声明一个 Feed 看起来很类似;这都是预先设计好的。

如同 Feed 类一样, Sitemap 成员也既可以是方法,也可以是属性。

一个 Sitemap 类可以定义如下 方法/属性:

    items (必需 ):提供对象列表。 框架并不关心对象的 类型 ;唯一关心的是这些对象会传递给 location() , lastmod() , changefreq() ,和 priority() 方法。

    location (可选): 给定对象的绝对URL。 绝对URL不包含协议名称和域名。 下面是一些例子:

  •         好的: '/foo/bar/' '/foo/bar/'
  •         差的: 'example.com/foo/bar/' 'example.com/foo/bar/'

    如果没有提供 location , 框架将会在每个 items() 返回的对象上调用 get_absolute_url() 方法.

    lastmod (可选): 对象的最后修改日期, 作为一个Python datetime 对象. The object's last modification date, as a Python datetime object.

    changefreq (可选): 对象变更的频率。 可选的值如下(详见Sitemaps文档):

  •         'always'
  •         'hourly'
  •         'daily'
  •         'weekly'
  •         'monthly'
  •         'yearly'
  •         'never'
  •     priority (可选): 取值范围在 0.0 and 1.0 之间,用来表明优先级。

快捷方式

sitemap框架提供了一些常用的类。 在下一部分中会看到。
FlatPageSitemap

django.contrib.sitemaps.FlatPageSitemap 类涉及到站点中所有的flat page,并在sitemap中建立一个入口。 但仅仅只包含 location 属性,不支持 lastmod , changefreq ,或者 priority 。

GenericSitemap

GenericSitemap 与所有的通用视图一同工作(详见第9章)。

你可以如下使用它,创建一个实例,并通过 info_dict 传递给通用视图。 唯一的要求是字典包含 queryset 这一项。 也可以用 date_field 来指明从 queryset 中取回的对象的日期域。 这会被用作站点地图中的 lastmod 属性。

下面是一个使用 FlatPageSitemap and GenericSiteMap (包括前面所假定的 Entry 对象)的URLconf:

from django.conf.urls.defaults import *
from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
from mysite.blog.models import Entry

info_dict = {
  'queryset': Entry.objects.all(),
  'date_field': 'pub_date',
}

sitemaps = {
  'flatpages': FlatPageSitemap,
  'blog': GenericSitemap(info_dict, priority=0.6),
}

urlpatterns = patterns('',
  # some generic view using info_dict
  # ...

  # the sitemap
  (r'^sitemap\.xml$',
   'django.contrib.sitemaps.views.sitemap',
   {'sitemaps': sitemaps})
)

创建一个Sitemap索引

sitemap框架同样可以根据 sitemaps 字典中定义的单独的sitemap文件来建立索引。 用法区别如下:

    您在您的URLconf 中使用了两个视图: django.contrib.sitemaps.views.index 和 django.contrib.sitemaps.views.sitemap . `` django.contrib.sitemaps.views.index`` 和`` django.contrib.sitemaps.views.sitemap``

    django.contrib.sitemaps.views.sitemap 视图需要带一个 section 关键字参数.

这里是前面的例子的相关的 URLconf 行看起来的样子:

(r'^sitemap.xml$',
 'django.contrib.sitemaps.views.index',
 {'sitemaps': sitemaps}),

(r'^sitemap-(?P<section>.+).xml$',
 'django.contrib.sitemaps.views.sitemap',
 {'sitemaps': sitemaps})

这将自动生成一个 sitemap.xml 文件, 它同时引用 sitemap-flatpages.xml 和 sitemap-blog.xml . Sitemap 类和 sitemaps 目录根本没有更改.
通知Google

当你的sitemap变化的时候,你会想通知Google,以便让它知道对你的站点进行重新索引。 框架就提供了这样的一个函数: django.contrib.sitemaps.ping_google() 。

ping_google() 有一个可选的参数 sitemap_url ,它应该是你的站点地图的URL绝对地址(例如:

如果不能够确定你的sitemap URL, ping_google() 会引发 django.contrib.sitemaps.SitemapNotFound 异常。

我们可以通过模型中的 save() 方法来调用 ping_google() :

from django.contrib.sitemaps import ping_google

class Entry(models.Model):
  # ...
  def save(self, *args, **kwargs):
    super(Entry, self).save(*args, **kwargs)
    try:
      ping_google()
    except Exception:
      # Bare 'except' because we could get a variety
      # of HTTP-related exceptions.
      pass

一个更有效的解决方案是用 cron 脚本或任务调度表来调用 ping_google() ,该方法使用Http直接请求Google服务器,从而减少每次调用 save() 时占用的网络带宽。 The function makes an HTTP request to Google's servers, so you may not want to introduce that network overhead each time you call save() .

Finally, if 'django.contrib.sitemaps' is in your INSTALLED_APPS , then your manage.py will include a new command, ping_google . This is useful for command-line access to pinging. For example:

python manage.py ping_google /sitemap.xml

Python 相关文章推荐
基于Python实现通过微信搜索功能查看谁把你删除了
Jan 27 Python
Python处理JSON时的值报错及编码报错的两则解决实录
Jun 26 Python
Python使用matplotlib绘制余弦的散点图示例
Mar 14 Python
python 集合 并集、交集 Series list set 转换的实例
May 29 Python
python try 异常处理(史上最全)
Mar 07 Python
python pandas cumsum求累计次数的用法
Jul 29 Python
利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式
Jan 20 Python
pyecharts动态轨迹图的实现示例
Apr 17 Python
Django 解决新建表删除后无法重新创建等问题
May 21 Python
python名片管理系统开发
Jun 18 Python
pytorch VGG11识别cifar10数据集(训练+预测单张输入图片操作)
Jun 24 Python
Python turtle实现贪吃蛇游戏
Jun 18 Python
用Python的Django框架来制作一个RSS阅读器
Jul 22 #Python
利用Python的Django框架生成PDF文件的教程
Jul 22 #Python
在Python的Django框架中生成CSV文件的方法
Jul 22 #Python
在主机商的共享服务器上部署Django站点的方法
Jul 22 #Python
在Lighttpd服务器中运行Django应用的方法
Jul 22 #Python
简单的Apache+FastCGI+Django配置指南
Jul 22 #Python
使用FastCGI部署Python的Django应用的教程
Jul 22 #Python
You might like
Thinkphp 框架扩展之驱动扩展实例分析
2020/04/27 PHP
javascript YUI 读码日记之 YAHOO.util.Dom - Part.4
2008/03/22 Javascript
javascript form 验证函数 弹出对话框形式
2009/06/23 Javascript
extjs 学习笔记 四 带分页的grid
2009/10/20 Javascript
javascript 放大镜 v1.0 基于Yui2 实现的放大镜效果
2010/03/08 Javascript
js 判断计算字符串长度/判断空的简单方法
2013/08/05 Javascript
javascript获取select的当前值示例代码(兼容IE/Firefox/Opera/Chrome)
2013/12/17 Javascript
jQuery源码解读之removeAttr()方法分析
2015/02/20 Javascript
手机端点击图片放大特效PhotoSwipe.js插件实现
2016/08/24 Javascript
原生js编写基于面向对象的分页组件
2016/12/05 Javascript
微信小程序之仿微信漂流瓶实例
2016/12/09 Javascript
Angular4绑定html内容出现警告的处理方法
2017/11/03 Javascript
jQuery实现通过方向键控制div块上下左右移动的方法【测试可用】
2018/04/26 jQuery
Bootstrap fileinput 上传新文件移除时触发服务器同步删除的配置
2018/10/08 Javascript
原生js实现获取form表单数据代码实例
2019/03/27 Javascript
mock.js模拟数据实现前后端分离
2019/07/24 Javascript
nodejs环境使用Typeorm连接查询Oracle数据
2019/12/05 NodeJs
Javascript中的this,bind和that使用实例
2019/12/05 Javascript
[02:51]DOTA2 Supermajor小组分组对阵抽签仪式
2018/06/01 DOTA
python监控文件或目录变化
2016/06/07 Python
网站渗透常用Python小脚本查询同ip网站
2017/05/08 Python
浅谈python装饰器探究与参数的领取
2017/12/01 Python
python保存数据到本地文件的方法
2018/06/23 Python
Ubuntu下升级 python3.7.1流程备忘(推荐)
2018/12/10 Python
浅谈python3发送post请求参数为空的情况
2018/12/28 Python
详解Python文件修改的两种方式
2019/08/22 Python
Python 内置函数globals()和locals()对比详解
2019/12/23 Python
使用Python制作新型冠状病毒实时疫情图
2020/01/28 Python
python中return不返回值的问题解析
2020/07/22 Python
CSS3选择器新增问题的实现
2021/01/21 HTML / CSS
机械设计及其自动化求职推荐信
2014/02/17 职场文书
个人批评与自我批评
2014/10/15 职场文书
党的群众路线教育实践活动实施方案
2014/10/31 职场文书
中考学习决心书
2015/02/04 职场文书
一个家长教育孩子的心得体会
2016/01/15 职场文书
vue @ ~ 相对路径 路径别名设置方式
2022/06/05 Vue.js