""" DjangoBlog 站点地图配置模块 功能:为搜索引擎提供网站结构地图,支持文章、分类、标签等内容的自动索引 """ from django.contrib.sitemaps import Sitemap from django.urls import reverse from blog.models import Article, Category, Tag class StaticViewSitemap(Sitemap): """ 静态页面站点地图 用于生成固定页面的站点地图,如首页等 """ # 优先级:0.5(中等优先级,首页等重要页面可以设为1.0) priority = 0.5 # 更新频率:每天检查 changefreq = 'daily' def items(self): """ 返回包含在站点地图中的静态页面名称 这些名称需要与 urls.py 中的 URL 名称对应 """ return ['blog:index', ] # 博客首页 def location(self, item): """ 根据页面名称生成完整的 URL 地址 """ return reverse(item) class ArticleSiteMap(Sitemap): """ 文章站点地图 自动生成所有已发布文章的站点地图 """ # 更新频率:每月检查(文章内容相对稳定) changefreq = "monthly" # 优先级:0.6(文章是核心内容,优先级较高) priority = "0.6" def items(self): """ 返回所有已发布的文章对象 status='p' 表示已发布状态 """ return Article.objects.filter(status='p') def lastmod(self, obj): """ 返回文章的最后修改时间 帮助搜索引擎了解内容更新情况 """ return obj.last_modify_time class CategorySiteMap(Sitemap): """ 分类站点地图 生成文章分类页面的站点地图 """ # 更新频率:每周检查(分类结构相对稳定) changefreq = "Weekly" # 优先级:0.6(分类页面重要程度较高) priority = "0.6" def items(self): """ 返回所有分类对象 """ return Category.objects.all() def lastmod(self, obj): """ 返回分类的最后修改时间 当分类下的文章更新时,分类页面也需要更新 """ return obj.last_modify_time class TagSiteMap(Sitemap): """ 标签站点地图 生成标签页面的站点地图 """ # 更新频率:每周检查 changefreq = "Weekly" # 优先级:0.3(标签页面重要性相对较低) priority = "0.3" def items(self): """ 返回所有标签对象 """ return Tag.objects.all() def lastmod(self, obj): """ 返回标签的最后修改时间 当标签关联的文章更新时,标签页面也需要更新 """ return obj.last_modify_time class UserSiteMap(Sitemap): """ 用户站点地图 生成用户主页的站点地图 """ # 更新频率:每周检查 changefreq = "Weekly" # 优先级:0.3(用户页面重要性相对较低) priority = "0.3" def items(self): """ 返回所有发表过文章的用户(作者) 使用 set 去重,确保每个用户只出现一次 """ return list(set(map(lambda x: x.author, Article.objects.all()))) def lastmod(self, obj): """ 返回用户的注册时间 这里使用用户注册时间作为最后修改时间 实际可以根据用户最后活动时间优化 """ return obj.date_joined