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根据时间获取周数代码实例

时间 时间和周数 import time import datetime # 获取今天是第几周 print(time.strftime('%W')) # 获取当前是周几(0-6,0...

Python实现的合并两个有序数组算法示例

本文实例讲述了Python实现的合并两个有序数组算法。分享给大家供大家参考,具体如下: 思路 按位循环比较两个数组,较小元素的放入新数组,下标加一(注意,较大元素对应的下标不加一),直到...

使用pip安装python库的多种方式

操作系统 : CentOS7.5.1804_x64 Python 版本 : 3.6.8 1、使用pip在线安装 1.1 安装单个package 格式如下: pip install Som...

Python 加密的实例详解

 Python 加密的实例详解 hashlib支持md5,sha1,sha256,sha384,sha512,用法和md5一样  import hashlib...

Python使用win32com实现的模拟浏览器功能示例

本文实例讲述了Python使用win32com实现的模拟浏览器功能。分享给大家供大家参考,具体如下: # -*- coding:UTF-8 -*- #!/user/bin/env p...