Django添加sitemap的方法示例

yipeiwu_com5年前Python基础

sitemap是 Google 最先引入的网站地图协议,采用 XML 格式,它的作用简而言之就是优化搜索引擎的索引效率,详细的解释可以参考百度百科

下面介绍下如何为Django站点添加sitemap功能。

1、启用sitemap

在django的settings.py的INSTALLED_APPS中添加

'django.contrib.sites',
'django.contrib.sitemaps',

然后migrate数据库:

$ ./manage.py makemigrations
$ ./manage.py migrate

登陆Django后台,修改SITE为你Django网站的域名和名称,然后在settings.py中加入SITE_ID = 1来制定当前的站点。

2、添加sitemap功能

(1)创建sitemap

创建sitemap.py.内容类似下面的代码:

from django.contrib.sitemaps import Sitemap
from blog.models import Article, Category, Tag
from accounts.models import BlogUser
from django.contrib.sitemaps import GenericSitemap
from django.core.urlresolvers import reverse

class StaticViewSitemap(Sitemap):
 priority = 0.5
 changefreq = 'daily'

 def items(self):
  return ['blog:index', ]

 def location(self, item):
  return reverse(item)


class ArticleSiteMap(Sitemap):
 changefreq = "monthly"
 priority = "0.6"

 def items(self):
  return Article.objects.filter(status='p')

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


class CategorySiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.6"

 def items(self):
  return Category.objects.all()

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


class TagSiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.3"

 def items(self):
  return Tag.objects.all()

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


class UserSiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.3"

 def items(self):
  return BlogUser.objects.all()

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

(2)url配置

url.py中加入:

from DjangoBlog.sitemap import StaticViewSitemap, ArticleSiteMap, CategorySiteMap, TagSiteMap, UserSiteMap

sitemaps = {

 'blog': ArticleSiteMap,
 'Category': CategorySiteMap,
 'Tag': TagSiteMap,
 'User': UserSiteMap,
 'static': StaticViewSitemap
}

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

至此,全部完成,运行你的django程序,浏览器输入:http://127.0.0.1:8000/sitemap.xml

就可以看见已经成功生成了,然后就可以提交这个地址给搜索引擎。 我的网站的sitemap的地址是:https://www.fkomm.cn/sitemap.xml

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中使用pyhook实现键盘监控的例子

pyhook下载:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/ pyhookAPI手册:http://pyhook...

python数据结构之链表详解

python数据结构之链表详解

数据结构是计算机科学必须掌握的一门学问,之前很多的教材都是用C语言实现链表,因为c有指针,可以很方便的控制内存,很方便就实现链表,其他的语言,则没那么方便,有很多都是用模拟链表,不过这次...

关于Django外键赋值问题详解

本文主要给大家介绍关于Django外键赋值的相关内容,分享出来供大家参考学习,在开始之前,我们先来看一段代码: class Article(models.Model): title...

使用Python+Splinter自动刷新抢12306火车票

使用Python+Splinter自动刷新抢12306火车票

一年一度的春运又来了,今年我自己写了个抢票脚本。使用Python+Splinter自动刷新抢票,可以成功抢到。(依赖自己的网络环境太厉害,还有机器的好坏) Splinter是一个使用Py...

Python和GO语言实现的消息摘要算法示例

Python和GO语言实现的消息摘要算法示例

常用的消息摘要算法有MD5和SHA,这些算法在python和go的库中都有,需要时候调用下就OK了,这里总结下python和go的实现。 一、python消息摘要示例 代码如下: 复制代...