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/feeds.py

97 lines
4.1 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 导入必要模块
from django.contrib.auth import get_user_model #wr 获取项目自定义的用户模型避免直接引用User类
from django.contrib.syndication.views import Feed #wr Django内置的RSS/Atom订阅生成基类
from django.utils import timezone #wr 处理时间相关操作(用于生成版权信息中的年份)
from django.utils.feedgenerator import Rss201rev2Feed #wr RSS 2.0标准格式生成器
from blog.models import Article #wr 博客文章模型RSS订阅的核心内容来源
from djangoblog.utils import CommonMarkdown #wr 自定义Markdown转换工具将Markdown转为HTML
class DjangoBlogFeed(Feed):
"""
wr自定义RSS订阅生成类继承自Django的Feed基类
用于生成博客文章的RSS订阅内容支持标准RSS 2.0格式
访问路径为/feed/,用户可通过订阅工具获取最新文章推送
"""
#wr 指定RSS订阅的格式版本采用RSS 2.0标准(兼容性最广)
feed_type = Rss201rev2Feed
#wr RSS订阅的描述信息将显示在订阅工具的描述栏
description = '大巧无工,重剑无锋.'
#wr RSS订阅的标题显示在订阅工具的标题栏
title = "且听风吟 大巧无工,重剑无锋. "
#wr RSS订阅的访问URL路径与urls.py中配置的路由一致
link = "/feed/"
def author_name(self):
"""
wr订阅内容的作者名称
这里取项目中第一个用户的昵称(默认作者,可根据实际需求修改)
:return: 作者昵称字符串
"""
return get_user_model().objects.first().nickname
def author_link(self):
"""
wr作者的个人页面链接
调用用户模型的get_absolute_url方法生成作者个人主页URL
:return: 作者个人页面的绝对URL
"""
return get_user_model().objects.first().get_absolute_url()
def items(self):
"""
wrRSS订阅的核心内容列表即要推送的文章
过滤条件类型为文章type='a'、状态为已发布status='p'
排序规则:按发布时间倒序(最新文章优先)
数量限制仅取前5篇避免订阅内容过多
:return: 筛选后的文章查询集
"""
return Article.objects.filter(type='a', status='p').order_by('-pub_time')[:5]
def item_title(self, item):
"""
wr单个订阅项文章的标题
直接使用文章自身的标题
:param item: 单个Article模型实例
:return: 文章标题字符串
"""
return item.title
def item_description(self, item):
"""
wr单个订阅项文章的描述内容
将文章的Markdown格式正文转换为HTMLRSS支持HTML格式确保排版正常
:param item: 单个Article模型实例
:return: 转换后的HTML格式文章内容
"""
return CommonMarkdown.get_markdown(item.body)
def feed_copyright(self):
"""
wr订阅内容的版权声明
动态获取当前年份,生成格式为"Copyright© 年份 且听风吟"的版权信息
:return: 版权声明字符串
"""
now = timezone.now()
return "Copyright© {year} 且听风吟".format(year=now.year)
def item_link(self, item):
"""
wr单个订阅项文章的访问链接
调用文章模型的get_absolute_url方法生成文章详情页的绝对URL
:param item: 单个Article模型实例
:return: 文章详情页的绝对URL
"""
return item.get_absolute_url()
def item_guid(self, item):
"""
wr单个订阅项文章的唯一标识GUID
用于订阅工具区分不同文章,避免重复推送
原代码未完成实现建议返回文章的唯一标识如文章ID+URL组合或绝对URL
示例实现return f"{item.get_absolute_url()}?id={item.id}"
:param item: 单个Article模型实例
:return: 文章的唯一标识字符串
"""
return #wr 原代码未完成,需根据实际需求补充唯一标识逻辑