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 zip()函数使用方法解析

这篇文章主要介绍了python zip()函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 参数iterable为可迭代...

flask使用session保存登录状态及拦截未登录请求代码

本文主要研究的是flask使用session保存登录状态及拦截未登录请求的相关内容,具体介绍如下。 前端请求form: <form action="/user/add" met...

Python简单计算给定某一年的某一天是星期几示例

Python简单计算给定某一年的某一天是星期几示例

本文实例讲述了Python简单计算给定某一年的某一天是星期几。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #计算某特定天使星期几 #蔡勒公式:w=...

python3获取url文件大小示例代码

python3获取url文件大小示例代码

在python3中,urllib2被替换为urllib.requeset,因此头文件中添加 import urllib.request as urllib2 def getRemot...

简单介绍Python中的RSS处理

RSS 是一个可用多种扩展来表示的缩写:“RDF 站点摘要(RDF Site Summary)”、“真正简单的辛迪加(Really Simple Syndication)”、“丰富站点摘...