master
parent
5b0854e397
commit
2e62fc2db4
@ -1 +1,2 @@
|
|||||||
|
# Zxy指定默认的应用配置类
|
||||||
default_app_config = 'djangoblog.apps.DjangoblogAppConfig'
|
default_app_config = 'djangoblog.apps.DjangoblogAppConfig'
|
||||||
|
|||||||
@ -1,40 +1,54 @@
|
|||||||
|
# Zxy导入Django的用户模型
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
|
# Zxy导入Django的Feed视图
|
||||||
from django.contrib.syndication.views import Feed
|
from django.contrib.syndication.views import Feed
|
||||||
|
# Zxy导入Django的时区工具
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
# Zxy导入RSS 2.0 Feed生成器
|
||||||
from django.utils.feedgenerator import Rss201rev2Feed
|
from django.utils.feedgenerator import Rss201rev2Feed
|
||||||
|
|
||||||
|
# Zxy导入项目中的文章模型
|
||||||
from blog.models import Article
|
from blog.models import Article
|
||||||
|
# Zxy导入Markdown工具
|
||||||
from djangoblog.utils import CommonMarkdown
|
from djangoblog.utils import CommonMarkdown
|
||||||
|
|
||||||
|
# Zxy定义Django博客Feed
|
||||||
class DjangoBlogFeed(Feed):
|
class DjangoBlogFeed(Feed):
|
||||||
feed_type = Rss201rev2Feed
|
feed_type = Rss201rev2Feed # Zxy使用RSS 2.0格式
|
||||||
|
|
||||||
description = '大巧无工,重剑无锋.'
|
description = '大巧无工,重剑无锋.' # ZxyFeed描述
|
||||||
title = "且听风吟 大巧无工,重剑无锋. "
|
title = "且听风吟 大巧无工,重剑无锋." # ZxyFeed标题
|
||||||
link = "/feed/"
|
link = "/feed/" # ZxyFeed链接
|
||||||
|
|
||||||
|
# Zxy获取作者名称
|
||||||
def author_name(self):
|
def author_name(self):
|
||||||
return get_user_model().objects.first().nickname
|
return get_user_model().objects.first().nickname
|
||||||
|
|
||||||
|
# Zxy获取作者链接
|
||||||
def author_link(self):
|
def author_link(self):
|
||||||
return get_user_model().objects.first().get_absolute_url()
|
return get_user_model().objects.first().get_absolute_url()
|
||||||
|
|
||||||
|
# Zxy获取Feed项
|
||||||
def items(self):
|
def items(self):
|
||||||
return Article.objects.filter(type='a', status='p').order_by('-pub_time')[:5]
|
return Article.objects.filter(type='a', status='p').order_by('-pub_time')[:5] # Zxy获取最近5篇已发布的文章
|
||||||
|
|
||||||
|
# Zxy获取Feed项标题
|
||||||
def item_title(self, item):
|
def item_title(self, item):
|
||||||
return item.title
|
return item.title
|
||||||
|
|
||||||
|
# Zxy获取Feed项描述
|
||||||
def item_description(self, item):
|
def item_description(self, item):
|
||||||
return CommonMarkdown.get_markdown(item.body)
|
return CommonMarkdown.get_markdown(item.body) # Zxy将文章内容转换为Markdown格式
|
||||||
|
|
||||||
|
# Zxy获取Feed版权信息
|
||||||
def feed_copyright(self):
|
def feed_copyright(self):
|
||||||
now = timezone.now()
|
now = timezone.now()
|
||||||
return "Copyright© {year} 且听风吟".format(year=now.year)
|
return "Copyright© {year} 且听风吟".format(year=now.year) # Zxy动态生成版权年份
|
||||||
|
|
||||||
|
# Zxy获取Feed项链接
|
||||||
def item_link(self, item):
|
def item_link(self, item):
|
||||||
return item.get_absolute_url()
|
return item.get_absolute_url()
|
||||||
|
|
||||||
|
# Zxy获取Feed项GUID
|
||||||
def item_guid(self, item):
|
def item_guid(self, item):
|
||||||
return
|
return
|
||||||
@ -1,91 +1,88 @@
|
|||||||
|
# Zxy导入Django的admin模块
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
# Zxy导入Django的LogEntry模型
|
||||||
from django.contrib.admin.models import DELETION
|
from django.contrib.admin.models import DELETION
|
||||||
|
# Zxy导入Django的内容类型模型
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
|
# Zxy导入Django的URL工具
|
||||||
from django.urls import reverse, NoReverseMatch
|
from django.urls import reverse, NoReverseMatch
|
||||||
|
# Zxy导入Django的编码工具
|
||||||
from django.utils.encoding import force_str
|
from django.utils.encoding import force_str
|
||||||
|
# Zxy导入Django的HTML工具
|
||||||
from django.utils.html import escape
|
from django.utils.html import escape
|
||||||
|
# Zxy导入Django的安全字符串工具
|
||||||
from django.utils.safestring import mark_safe
|
from django.utils.safestring import mark_safe
|
||||||
|
# Zxy导入Django的翻译工具
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
# Zxy定义LogEntryAdmin类
|
||||||
class LogEntryAdmin(admin.ModelAdmin):
|
class LogEntryAdmin(admin.ModelAdmin):
|
||||||
list_filter = [
|
list_filter = ['content_type'] # Zxy按内容类型过滤
|
||||||
'content_type'
|
search_fields = ['object_repr', 'change_message'] # Zxy搜索字段
|
||||||
]
|
|
||||||
|
|
||||||
search_fields = [
|
|
||||||
'object_repr',
|
|
||||||
'change_message'
|
|
||||||
]
|
|
||||||
|
|
||||||
list_display_links = [
|
list_display_links = ['action_time', 'get_change_message'] # Zxy显示链接的字段
|
||||||
'action_time',
|
list_display = ['action_time', 'user_link', 'content_type', 'object_link', 'get_change_message'] # Zxy显示字段
|
||||||
'get_change_message',
|
|
||||||
]
|
|
||||||
list_display = [
|
|
||||||
'action_time',
|
|
||||||
'user_link',
|
|
||||||
'content_type',
|
|
||||||
'object_link',
|
|
||||||
'get_change_message',
|
|
||||||
]
|
|
||||||
|
|
||||||
|
# Zxy检查是否有添加权限
|
||||||
def has_add_permission(self, request):
|
def has_add_permission(self, request):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Zxy检查是否有修改权限
|
||||||
def has_change_permission(self, request, obj=None):
|
def has_change_permission(self, request, obj=None):
|
||||||
return (
|
return (
|
||||||
request.user.is_superuser or
|
request.user.is_superuser or
|
||||||
request.user.has_perm('admin.change_logentry')
|
request.user.has_perm('admin.change_logentry')
|
||||||
) and request.method != 'POST'
|
) and request.method != 'POST'
|
||||||
|
|
||||||
|
# Zxy检查是否有删除权限
|
||||||
def has_delete_permission(self, request, obj=None):
|
def has_delete_permission(self, request, obj=None):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Zxy获取对象链接
|
||||||
def object_link(self, obj):
|
def object_link(self, obj):
|
||||||
object_link = escape(obj.object_repr)
|
object_link = escape(obj.object_repr) # Zxy转义对象表示
|
||||||
content_type = obj.content_type
|
content_type = obj.content_type
|
||||||
|
|
||||||
if obj.action_flag != DELETION and content_type is not None:
|
if obj.action_flag != DELETION and content_type is not None: # Zxy检查是否为删除操作
|
||||||
# try returning an actual link instead of object repr string
|
|
||||||
try:
|
try:
|
||||||
url = reverse(
|
url = reverse( # Zxy生成反向URL
|
||||||
'admin:{}_{}_change'.format(content_type.app_label,
|
'admin:{}_{}_change'.format(content_type.app_label, content_type.model),
|
||||||
content_type.model),
|
|
||||||
args=[obj.object_id]
|
args=[obj.object_id]
|
||||||
)
|
)
|
||||||
object_link = '<a href="{}">{}</a>'.format(url, object_link)
|
object_link = '<a href="{}">{}</a>'.format(url, object_link) # Zxy生成链接
|
||||||
except NoReverseMatch:
|
except NoReverseMatch:
|
||||||
pass
|
pass
|
||||||
return mark_safe(object_link)
|
return mark_safe(object_link) # Zxy标记为安全字符串
|
||||||
|
|
||||||
object_link.admin_order_field = 'object_repr'
|
object_link.admin_order_field = 'object_repr' # Zxy排序字段
|
||||||
object_link.short_description = _('object')
|
object_link.short_description = _('object') # Zxy字段描述
|
||||||
|
|
||||||
|
# Zxy获取用户链接
|
||||||
def user_link(self, obj):
|
def user_link(self, obj):
|
||||||
content_type = ContentType.objects.get_for_model(type(obj.user))
|
content_type = ContentType.objects.get_for_model(type(obj.user)) # Zxy获取用户的内容类型
|
||||||
user_link = escape(force_str(obj.user))
|
user_link = escape(force_str(obj.user)) # Zxy转义用户表示
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# try returning an actual link instead of object repr string
|
url = reverse( # Zxy生成反向URL
|
||||||
url = reverse(
|
'admin:{}_{}_change'.format(content_type.app_label, content_type.model),
|
||||||
'admin:{}_{}_change'.format(content_type.app_label,
|
|
||||||
content_type.model),
|
|
||||||
args=[obj.user.pk]
|
args=[obj.user.pk]
|
||||||
)
|
)
|
||||||
user_link = '<a href="{}">{}</a>'.format(url, user_link)
|
user_link = '<a href="{}">{}</a>'.format(url, user_link) # Zxy生成链接
|
||||||
except NoReverseMatch:
|
except NoReverseMatch:
|
||||||
pass
|
pass
|
||||||
return mark_safe(user_link)
|
return mark_safe(user_link) # Zxy标记为安全字符串
|
||||||
|
|
||||||
user_link.admin_order_field = 'user'
|
user_link.admin_order_field = 'user' # Zxy排序字段
|
||||||
user_link.short_description = _('user')
|
user_link.short_description = _('user') # Zxy字段描述
|
||||||
|
|
||||||
|
# Zxy获取查询集
|
||||||
def get_queryset(self, request):
|
def get_queryset(self, request):
|
||||||
queryset = super(LogEntryAdmin, self).get_queryset(request)
|
queryset = super(LogEntryAdmin, self).get_queryset(request)
|
||||||
return queryset.prefetch_related('content_type')
|
return queryset.prefetch_related('content_type') # Zxy预加载内容类型
|
||||||
|
|
||||||
|
# Zxy获取操作
|
||||||
def get_actions(self, request):
|
def get_actions(self, request):
|
||||||
actions = super(LogEntryAdmin, self).get_actions(request)
|
actions = super(LogEntryAdmin, self).get_actions(request)
|
||||||
if 'delete_selected' in actions:
|
if 'delete_selected' in actions: # Zxy移除删除操作
|
||||||
del actions['delete_selected']
|
del actions['delete_selected']
|
||||||
return actions
|
return actions
|
||||||
@ -1,7 +1,8 @@
|
|||||||
ARTICLE_DETAIL_LOAD = 'article_detail_load'
|
# Zxy定义文章相关的钩子常量
|
||||||
ARTICLE_CREATE = 'article_create'
|
ARTICLE_DETAIL_LOAD = 'article_detail_load' # Zxy文章详情加载时触发的钩子
|
||||||
ARTICLE_UPDATE = 'article_update'
|
ARTICLE_CREATE = 'article_create' # Zxy文章创建时触发的钩子
|
||||||
ARTICLE_DELETE = 'article_delete'
|
ARTICLE_UPDATE = 'article_update' # Zxy文章更新时触发的钩子
|
||||||
|
ARTICLE_DELETE = 'article_delete' # Zxy文章删除时触发的钩子
|
||||||
ARTICLE_CONTENT_HOOK_NAME = "the_content"
|
|
||||||
|
|
||||||
|
# Zxy定义文章内容处理的钩子名称
|
||||||
|
ARTICLE_CONTENT_HOOK_NAME = "the_content" # Zxy文章内容处理的钩子名称
|
||||||
@ -1,44 +1,47 @@
|
|||||||
|
# Zxy导入日志模块
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
# Zxy获取日志记录器
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Zxy定义全局钩子字典
|
||||||
_hooks = {}
|
_hooks = {}
|
||||||
|
|
||||||
|
# Zxy注册钩子回调
|
||||||
def register(hook_name: str, callback: callable):
|
def register(hook_name: str, callback: callable):
|
||||||
"""
|
"""
|
||||||
注册一个钩子回调。
|
注册一个钩子回调。
|
||||||
"""
|
"""
|
||||||
if hook_name not in _hooks:
|
if hook_name not in _hooks: # Zxy检查钩子是否已存在
|
||||||
_hooks[hook_name] = []
|
_hooks[hook_name] = [] # Zxy初始化钩子列表
|
||||||
_hooks[hook_name].append(callback)
|
_hooks[hook_name].append(callback) # Zxy添加回调到钩子列表
|
||||||
logger.debug(f"Registered hook '{hook_name}' with callback '{callback.__name__}'")
|
logger.debug(f"Registered hook '{hook_name}' with callback '{callback.__name__}'") # Zxy记录注册日志
|
||||||
|
|
||||||
|
|
||||||
|
# Zxy执行Action Hook
|
||||||
def run_action(hook_name: str, *args, **kwargs):
|
def run_action(hook_name: str, *args, **kwargs):
|
||||||
"""
|
"""
|
||||||
执行一个 Action Hook。
|
执行一个 Action Hook。
|
||||||
它会按顺序执行所有注册到该钩子上的回调函数。
|
它会按顺序执行所有注册到该钩子上的回调函数。
|
||||||
"""
|
"""
|
||||||
if hook_name in _hooks:
|
if hook_name in _hooks: # Zxy检查钩子是否存在
|
||||||
logger.debug(f"Running action hook '{hook_name}'")
|
logger.debug(f"Running action hook '{hook_name}'") # Zxy记录执行日志
|
||||||
for callback in _hooks[hook_name]:
|
for callback in _hooks[hook_name]: # Zxy遍历钩子回调
|
||||||
try:
|
try:
|
||||||
callback(*args, **kwargs)
|
callback(*args, **kwargs) # Zxy执行回调
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error running action hook '{hook_name}' callback '{callback.__name__}': {e}", exc_info=True)
|
logger.error(f"Error running action hook '{hook_name}' callback '{callback.__name__}': {e}", exc_info=True) # Zxy记录错误日志
|
||||||
|
|
||||||
|
|
||||||
|
# Zxy执行Filter Hook
|
||||||
def apply_filters(hook_name: str, value, *args, **kwargs):
|
def apply_filters(hook_name: str, value, *args, **kwargs):
|
||||||
"""
|
"""
|
||||||
执行一个 Filter Hook。
|
执行一个 Filter Hook。
|
||||||
它会把 value 依次传递给所有注册的回调函数进行处理。
|
它会把 value 依次传递给所有注册的回调函数进行处理。
|
||||||
"""
|
"""
|
||||||
if hook_name in _hooks:
|
if hook_name in _hooks: # Zxy检查钩子是否存在
|
||||||
logger.debug(f"Applying filter hook '{hook_name}'")
|
logger.debug(f"Applying filter hook '{hook_name}'") # Zxy记录执行日志
|
||||||
for callback in _hooks[hook_name]:
|
for callback in _hooks[hook_name]: # Zxy遍历钩子回调
|
||||||
try:
|
try:
|
||||||
value = callback(value, *args, **kwargs)
|
value = callback(value, *args, **kwargs) # Zxy调用回调处理值
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error applying filter hook '{hook_name}' callback '{callback.__name__}': {e}", exc_info=True)
|
logger.error(f"Error applying filter hook '{hook_name}' callback '{callback.__name__}': {e}", exc_info=True) # Zxy记录错误日志
|
||||||
return value
|
return value # Zxy返回处理后的值
|
||||||
@ -1,21 +1,26 @@
|
|||||||
|
# Zxy导入日志模块
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
# Zxy导入 requests 模块用于发送 HTTP 请求
|
||||||
import requests
|
import requests
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
|
# Zxy获取日志记录器
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Zxy定义爬虫通知类
|
||||||
class SpiderNotify():
|
class SpiderNotify():
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def baidu_notify(urls):
|
def baidu_notify(urls):
|
||||||
|
# Zxy向百度站长平台发送 URL 提交请求
|
||||||
try:
|
try:
|
||||||
data = '\n'.join(urls)
|
data = '\n'.join(urls) # Zxy将 URL 列表拼接为字符串
|
||||||
result = requests.post(settings.BAIDU_NOTIFY_URL, data=data)
|
result = requests.post(settings.BAIDU_NOTIFY_URL, data=data) # Zxy发送 POST 请求
|
||||||
logger.info(result.text)
|
logger.info(result.text) # Zxy记录响应内容
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(e)
|
logger.error(e) # Zxy记录异常信息
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def notify(url):
|
def notify(url):
|
||||||
|
# Zxy调用百度通知方法
|
||||||
SpiderNotify.baidu_notify(url)
|
SpiderNotify.baidu_notify(url)
|
||||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue