You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tentest/doc/DjangoBlog/djangoblog/sitemap.py

98 lines
3.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#wr 导入Django站点地图核心类及相关工具
from django.contrib.sitemaps import Sitemap # 站点地图基类,所有自定义站点地图需继承此类
from django.urls import reverse # URL反向解析工具用于生成页面URL
#wr 导入博客相关模型(站点地图需包含这些模型对应的页面)
from blog.models import Article, Category, Tag
class StaticViewSitemap(Sitemap):
"""
wr静态页面站点地图用于收录网站中固定不变的静态页面如首页
站点地图Sitemap用于告诉搜索引擎网站的页面结构帮助爬虫高效索引
"""
priority = 0.5
#wr 页面更新频率可选值always, hourly, daily, weekly, monthly, yearly, never
changefreq = 'daily' #wr 静态页面假设每日更新
def items(self):
"""
wr返回需要收录的静态页面视图名称列表
这里仅包含博客首页(视图名称为'blog:index'对应urls.py中的命名空间+名称)
"""
return ['blog:index', ]
def location(self, item):
"""
wr生成每个静态页面的URL
:param item: items()返回的视图名称(如'blog:index'
:return: 页面的绝对URL
"""
return reverse(item) # 通过reverse反向解析视图名称为URL
class ArticleSiteMap(Sitemap):
"""wr文章页面站点地图用于收录所有已发布的博客文章页面"""
changefreq = "monthly" #wr 文章页面更新频率设为每月(假设文章发布后较少修改)
priority = "0.6" #wr 文章页面优先级设为0.6(高于静态页面,低于核心页面)
def items(self):
"""wr返回需要收录的文章对象列表仅包含状态为"已发布"status='p')的文章"""
return Article.objects.filter(status='p')
def lastmod(self, obj):
"""
wr返回文章的最后修改时间供搜索引擎判断页面是否更新
:param obj: items()返回的Article实例
:return: 文章最后修改时间
"""
return obj.last_modify_time
class CategorySiteMap(Sitemap):
"""wr分类页面站点地图用于收录所有文章分类页面"""
changefreq = "Weekly" #wr 分类页面更新频率设为每周(分类信息较少变动)
priority = "0.6" #wr 分类页面优先级与文章页面相同
def items(self):
"""wr返回所有分类对象列表所有分类页面都需要被收录"""
return Category.objects.all()
def lastmod(self, obj):
"""wr返回分类的最后修改时间"""
return obj.last_modify_time
class TagSiteMap(Sitemap):
"""wr标签页面站点地图用于收录所有文章标签页面"""
changefreq = "Weekly" #wr 标签页面更新频率设为每周
priority = "0.3" #wr 标签页面优先级较低0.3),因为重要性低于文章和分类
def items(self):
"""wr返回所有标签对象列表所有标签页面都需要被收录"""
return Tag.objects.all()
def lastmod(self, obj):
"""wr返回标签的最后修改时间"""
return obj.last_modify_time
class UserSiteMap(Sitemap):
"""wr用户页面站点地图用于收录所有发表过文章的作者页面"""
changefreq = "Weekly" #v 用户页面更新频率设为每周
priority = "0.3" #wr 用户页面优先级较低
def items(self):
"""
wr返回所有发表过文章的作者列表去重处理
逻辑通过map提取所有已发布文章的作者再用set去重最后转为列表
"""
return list(set(map(lambda x: x.author, Article.objects.all())))
def lastmod(self, obj):
"""
wr返回用户相关的最后更新时间这里用用户注册时间代替也可改为用户最后发表文章时间
:param obj: items()返回的用户实例
:return: 用户注册时间
"""
return obj.date_joined