From eac243818d651281e841188481859d3e6e251cc8 Mon Sep 17 00:00:00 2001 From: dynastxu <151742029+ETOofficial@users.noreply.github.com> Date: Sun, 9 Nov 2025 00:06:10 +0800 Subject: [PATCH] Squashed 'src/DjangoBlog/' changes from 408d19c..13ebbc8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 13ebbc8 优化代码 git-subtree-dir: src/DjangoBlog git-subtree-split: 13ebbc80d2e3639d9271431d19b52afe889e8646 --- accounts/forms.py | 1 + accounts/migrations/0001_initial.py | 2 +- ...s_remove_bloguser_created_time_and_more.py | 2 +- accounts/models.py | 1 + accounts/tests.py | 7 ++-- accounts/utils.py | 1 + accounts/views.py | 5 ++- blog/admin.py | 10 ++--- blog/documents.py | 14 ++++--- blog/management/commands/ping_baidu.py | 5 ++- blog/management/commands/sync_user_avatar.py | 3 +- blog/middleware.py | 4 +- blog/migrations/0001_initial.py | 5 +-- ...options_alter_category_options_and_more.py | 5 +-- blog/templatetags/blog_tags.py | 10 ++--- blog/tests.py | 13 ++++--- blog/views.py | 37 +++++++++---------- comments/admin.py | 4 +- comments/migrations/0001_initial.py | 3 +- ...ns_remove_comment_created_time_and_more.py | 3 +- comments/tests.py | 3 +- djangoblog/blog_signals.py | 13 ++----- djangoblog/elasticsearch_backend.py | 6 ++- djangoblog/feeds.py | 12 ++++-- djangoblog/plugin_manage/base_plugin.py | 21 +++++++---- djangoblog/plugin_manage/loader.py | 3 +- djangoblog/sitemap.py | 12 ++++-- djangoblog/spider_notify.py | 2 +- djangoblog/urls.py | 7 ++-- djangoblog/utils.py | 12 +++--- djangoblog/whoosh_cn_backend.py | 30 ++++++++------- oauth/admin.py | 3 +- oauth/migrations/0001_initial.py | 3 +- ...ptions_alter_oauthuser_options_and_more.py | 3 +- oauth/oauthmanager.py | 13 +++++-- oauth/tests.py | 18 +++++---- owntracks/migrations/0001_initial.py | 2 +- owntracks/tests.py | 2 +- plugins/article_copyright/plugin.py | 5 ++- plugins/article_recommendation/plugin.py | 10 +++-- plugins/external_links/plugin.py | 6 ++- plugins/image_lazy_loading/plugin.py | 16 +++++--- plugins/reading_time/plugin.py | 6 ++- plugins/seo_optimizer/plugin.py | 18 +++++---- plugins/view_count/plugin.py | 5 ++- servermanager/api/blogapi.py | 3 +- servermanager/api/commonapi.py | 3 +- servermanager/robot.py | 16 ++++---- servermanager/tests.py | 7 ++-- 49 files changed, 220 insertions(+), 175 deletions(-) diff --git a/accounts/forms.py b/accounts/forms.py index fce4137..964466e 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -4,6 +4,7 @@ from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.core.exceptions import ValidationError from django.forms import widgets from django.utils.translation import gettext_lazy as _ + from . import utils from .models import BlogUser diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py index d2fbcab..884428e 100644 --- a/accounts/migrations/0001_initial.py +++ b/accounts/migrations/0001_initial.py @@ -2,8 +2,8 @@ import django.contrib.auth.models import django.contrib.auth.validators -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/accounts/migrations/0002_alter_bloguser_options_remove_bloguser_created_time_and_more.py b/accounts/migrations/0002_alter_bloguser_options_remove_bloguser_created_time_and_more.py index 1a9f509..854d366 100644 --- a/accounts/migrations/0002_alter_bloguser_options_remove_bloguser_created_time_and_more.py +++ b/accounts/migrations/0002_alter_bloguser_options_remove_bloguser_created_time_and_more.py @@ -1,7 +1,7 @@ # Generated by Django 4.2.5 on 2023-09-06 13:13 -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/accounts/models.py b/accounts/models.py index 3baddbb..855dfc8 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -3,6 +3,7 @@ from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ + from djangoblog.utils import get_current_site diff --git a/accounts/tests.py b/accounts/tests.py index 6893411..e962f67 100644 --- a/accounts/tests.py +++ b/accounts/tests.py @@ -1,7 +1,6 @@ from django.test import Client, RequestFactory, TestCase from django.urls import reverse from django.utils import timezone -from django.utils.translation import gettext_lazy as _ from accounts.models import BlogUser from blog.models import Article, Category @@ -23,12 +22,12 @@ class AccountTest(TestCase): self.new_test = "xxx123--=" def test_validate_account(self): - site = get_current_site().domain + get_current_site().domain user = BlogUser.objects.create_superuser( email="liangliangyy1@gmail.com", username="liangliangyy1", password="qwer!@#$ggg") - testuser = BlogUser.objects.get(username='liangliangyy1') + BlogUser.objects.get(username='liangliangyy1') loginresult = self.client.login( username='liangliangyy1', @@ -60,7 +59,7 @@ class AccountTest(TestCase): 0, len( BlogUser.objects.filter( email='user123@user.com'))) - response = self.client.post(reverse('account:register'), { + self.client.post(reverse('account:register'), { 'username': 'user1233', 'email': 'user123@user.com', 'password1': 'password123!q@wE#R$T', diff --git a/accounts/utils.py b/accounts/utils.py index 4b94bdf..d416b35 100644 --- a/accounts/utils.py +++ b/accounts/utils.py @@ -37,6 +37,7 @@ def verify(email: str, code: str) -> typing.Optional[str]: cache_code = get_code(email) if cache_code != code: return gettext("Verification code error") + return None def set_code(email: str, code: str): diff --git a/accounts/views.py b/accounts/views.py index ae67aec..e9c188e 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -1,5 +1,5 @@ import logging -from django.utils.translation import gettext_lazy as _ + from django.conf import settings from django.contrib import auth from django.contrib.auth import REDIRECT_FIELD_NAME @@ -191,7 +191,8 @@ class ForgetPasswordView(FormView): class ForgetPasswordEmailCode(View): - def post(self, request: HttpRequest): + @staticmethod + def post(request: HttpRequest): form = ForgetPasswordCodeForm(request.POST) if not form.is_valid(): return HttpResponse("错误的邮箱") diff --git a/blog/admin.py b/blog/admin.py index 69d7f8e..3207b63 100644 --- a/blog/admin.py +++ b/blog/admin.py @@ -6,7 +6,7 @@ from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ # Register your models here. -from .models import Article, Category, Tag, Links, SideBar, BlogSettings +from .models import Article class ArticleForm(forms.ModelForm): @@ -17,19 +17,19 @@ class ArticleForm(forms.ModelForm): fields = '__all__' -def makr_article_publish(modeladmin, request, queryset): +def makr_article_publish(queryset): queryset.update(status='p') -def draft_article(modeladmin, request, queryset): +def draft_article(queryset): queryset.update(status='d') -def close_article_commentstatus(modeladmin, request, queryset): +def close_article_commentstatus(queryset): queryset.update(comment_status='c') -def open_article_commentstatus(modeladmin, request, queryset): +def open_article_commentstatus(queryset): queryset.update(comment_status='o') diff --git a/blog/documents.py b/blog/documents.py index 0f1db7b..2b0c883 100644 --- a/blog/documents.py +++ b/blog/documents.py @@ -164,20 +164,23 @@ class ArticleDocument(Document): doc_type = 'Article' -class ArticleDocumentManager(): +class ArticleDocumentManager: def __init__(self): self.create_index() - def create_index(self): + @staticmethod + def create_index(): ArticleDocument.init() - def delete_index(self): + @staticmethod + def delete_index(): from elasticsearch import Elasticsearch es = Elasticsearch(settings.ELASTICSEARCH_DSL['default']['hosts']) es.indices.delete(index='blog', ignore=[400, 404]) - def convert_to_doc(self, articles): + @staticmethod + def convert_to_doc(articles): return [ ArticleDocument( meta={ @@ -208,6 +211,7 @@ class ArticleDocumentManager(): for doc in docs: doc.save() - def update_docs(self, docs): + @staticmethod + def update_docs(docs): for doc in docs: doc.save() diff --git a/blog/management/commands/ping_baidu.py b/blog/management/commands/ping_baidu.py index 2c7fbdd..0063ea1 100644 --- a/blog/management/commands/ping_baidu.py +++ b/blog/management/commands/ping_baidu.py @@ -1,8 +1,8 @@ from django.core.management.base import BaseCommand +from blog.models import Article, Tag, Category from djangoblog.spider_notify import SpiderNotify from djangoblog.utils import get_current_site -from blog.models import Article, Tag, Category site = get_current_site().domain @@ -21,7 +21,8 @@ class Command(BaseCommand): 'category'], help='article : all article,tag : all tag,category: all category,all: All of these') - def get_full_url(self, path): + @staticmethod + def get_full_url(path): url = "https://{site}{path}".format(site=site, path=path) return url diff --git a/blog/management/commands/sync_user_avatar.py b/blog/management/commands/sync_user_avatar.py index d0f4612..bab11b4 100644 --- a/blog/management/commands/sync_user_avatar.py +++ b/blog/management/commands/sync_user_avatar.py @@ -10,7 +10,8 @@ from oauth.oauthmanager import get_manager_by_type class Command(BaseCommand): help = 'sync user avatar' - def test_picture(self, url): + @staticmethod + def test_picture(url): try: if requests.get(url, timeout=2).status_code == 200: return True diff --git a/blog/middleware.py b/blog/middleware.py index 94dd70c..881c347 100644 --- a/blog/middleware.py +++ b/blog/middleware.py @@ -15,7 +15,7 @@ class OnlineMiddleware(object): super().__init__() def __call__(self, request): - ''' page render time ''' + """ page render time """ start_time = time.time() response = self.get_response(request) http_user_agent = request.META.get('HTTP_USER_AGENT', '') @@ -25,7 +25,7 @@ class OnlineMiddleware(object): try: cast_time = time.time() - start_time if ELASTICSEARCH_ENABLED: - time_taken = round((cast_time) * 1000, 2) + time_taken = round(cast_time * 1000, 2) url = request.path from django.utils import timezone ElaspedTimeDocumentManager.create( diff --git a/blog/migrations/0001_initial.py b/blog/migrations/0001_initial.py index 3d391b6..525c125 100644 --- a/blog/migrations/0001_initial.py +++ b/blog/migrations/0001_initial.py @@ -1,10 +1,9 @@ # Generated by Django 4.1.7 on 2023-03-02 07:14 -from django.conf import settings -from django.db import migrations, models -import django.db.models.deletion import django.utils.timezone import mdeditor.fields +from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/blog/migrations/0005_alter_article_options_alter_category_options_and_more.py b/blog/migrations/0005_alter_article_options_alter_category_options_and_more.py index d08e853..398a9c7 100644 --- a/blog/migrations/0005_alter_article_options_alter_category_options_and_more.py +++ b/blog/migrations/0005_alter_article_options_alter_category_options_and_more.py @@ -1,10 +1,9 @@ # Generated by Django 4.2.5 on 2023-09-06 13:13 -from django.conf import settings -from django.db import migrations, models -import django.db.models.deletion import django.utils.timezone import mdeditor.fields +from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/blog/templatetags/blog_tags.py b/blog/templatetags/blog_tags.py index 024f2c8..eb0800f 100644 --- a/blog/templatetags/blog_tags.py +++ b/blog/templatetags/blog_tags.py @@ -1,7 +1,5 @@ -import hashlib import logging import random -import urllib from django import template from django.conf import settings @@ -14,11 +12,11 @@ from django.utils.safestring import mark_safe from blog.models import Article, Category, Tag, Links, SideBar, LinkShowType from comments.models import Comment +from djangoblog.plugin_manage import hooks from djangoblog.utils import CommonMarkdown, sanitize_html from djangoblog.utils import cache from djangoblog.utils import get_current_site from oauth.models import OAuthUser -from djangoblog.plugin_manage import hooks logger = logging.getLogger(__name__) @@ -168,7 +166,7 @@ def load_breadcrumb(article): names = article.get_category_tree() from djangoblog.utils import get_blog_setting blogsetting = get_blog_setting() - site = get_current_site().domain + get_current_site().domain names.append((blogsetting.site_name, '/')) names = names[::-1] @@ -363,7 +361,7 @@ def load_article_detail(article, isindex, user): # 返回用户头像URL # 模板使用方法: {{ email|gravatar_url:150 }} @register.filter -def gravatar_url(email, size=40): +def gravatar_url(email): """获得用户头像 - 优先使用OAuth头像,否则使用默认头像""" cachekey = 'avatar/' + email url = cache.get(cachekey) @@ -400,7 +398,7 @@ def gravatar_url(email, size=40): @register.filter def gravatar(email, size=40): """获得用户头像HTML标签""" - url = gravatar_url(email, size) + url = gravatar_url(email) return mark_safe( '用户头像' % (url, size, size)) diff --git a/blog/tests.py b/blog/tests.py index ee13505..a9f2147 100644 --- a/blog/tests.py +++ b/blog/tests.py @@ -25,7 +25,7 @@ class ArticleTest(TestCase): self.factory = RequestFactory() def test_validate_article(self): - site = get_current_site().domain + get_current_site().domain user = BlogUser.objects.get_or_create( email="liangliangyy@gmail.com", username="liangliangyy")[0] @@ -35,8 +35,8 @@ class ArticleTest(TestCase): user.save() response = self.client.get(user.get_absolute_url()) self.assertEqual(response.status_code, 200) - response = self.client.get('/admin/servermanager/emailsendlog/') - response = self.client.get('admin/admin/logentry/') + self.client.get('/admin/servermanager/emailsendlog/') + self.client.get('admin/admin/logentry/') s = SideBar() s.sequence = 1 s.name = 'test' @@ -126,8 +126,8 @@ class ArticleTest(TestCase): SpiderNotify.baidu_notify([article.get_full_url()]) from blog.templatetags.blog_tags import gravatar_url, gravatar - u = gravatar_url('liangliangyy@gmail.com') - u = gravatar('liangliangyy@gmail.com') + gravatar_url('liangliangyy@gmail.com') + gravatar('liangliangyy@gmail.com') link = Links( sequence=1, @@ -186,7 +186,8 @@ class ArticleTest(TestCase): rsp = self.client.get('/eee') self.assertEqual(rsp.status_code, 404) - def test_commands(self): + @staticmethod + def test_commands(): user = BlogUser.objects.get_or_create( email="liangliangyy@gmail.com", username="liangliangyy")[0] diff --git a/blog/views.py b/blog/views.py index 773bb75..fd0a820 100644 --- a/blog/views.py +++ b/blog/views.py @@ -18,7 +18,6 @@ from haystack.views import SearchView from blog.models import Article, Category, LinkShowType, Links, Tag from comments.forms import CommentForm from djangoblog.plugin_manage import hooks -from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME from djangoblog.utils import cache, get_blog_setting, get_sha256 logger = logging.getLogger(__name__) @@ -60,11 +59,11 @@ class ArticleListView(ListView): raise NotImplementedError() def get_queryset_from_cache(self, cache_key): - ''' + """ 缓存页面数据 :param cache_key: 缓存key :return: - ''' + """ value = cache.get(cache_key) if value: logger.info('get view cache.key:{key}'.format(key=cache_key)) @@ -76,10 +75,10 @@ class ArticleListView(ListView): return article_list def get_queryset(self): - ''' + """ 重写默认,从缓存获取数据 :return: - ''' + """ key = self.get_queryset_cache_key() value = self.get_queryset_from_cache(key) return value @@ -90,9 +89,9 @@ class ArticleListView(ListView): class IndexView(ArticleListView): - ''' + """ 首页 - ''' + """ # 友情链接类型 link_type = LinkShowType.I @@ -106,9 +105,9 @@ class IndexView(ArticleListView): class ArticleDetailView(DetailView): - ''' + """ 文章详情页面 - ''' + """ template_name = 'blog/article_detail.html' model = Article pk_url_kwarg = 'article_id' @@ -163,9 +162,9 @@ class ArticleDetailView(DetailView): class CategoryDetailView(ArticleListView): - ''' + """ 分类目录列表 - ''' + """ page_type = "分类目录归档" def get_queryset_data(self): @@ -202,9 +201,9 @@ class CategoryDetailView(ArticleListView): class AuthorDetailView(ArticleListView): - ''' + """ 作者详情页 - ''' + """ page_type = '作者文章归档' def get_queryset_cache_key(self): @@ -228,9 +227,9 @@ class AuthorDetailView(ArticleListView): class TagDetailView(ArticleListView): - ''' + """ 标签列表页面 - ''' + """ page_type = '分类标签归档' def get_queryset_data(self): @@ -260,9 +259,9 @@ class TagDetailView(ArticleListView): class ArchivesView(ArticleListView): - ''' + """ 文章归档页面 - ''' + """ page_type = '文章归档' paginate_by = None page_kwarg = None @@ -347,7 +346,7 @@ def page_not_found_view( template_name='blog/error_page.html'): if exception: logger.error(exception) - url = request.get_full_path() + request.get_full_path() return render(request, template_name, {'message': _('Sorry, the page you requested is not found, please click the home page to see other?'), @@ -375,6 +374,6 @@ def permission_denied_view( 'statuscode': '403'}, status=403) -def clean_cache_view(request): +def clean_cache_view(): cache.clear() return HttpResponse('ok') diff --git a/comments/admin.py b/comments/admin.py index dbde14f..1e9bc73 100644 --- a/comments/admin.py +++ b/comments/admin.py @@ -4,11 +4,11 @@ from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ -def disable_commentstatus(modeladmin, request, queryset): +def disable_commentstatus(queryset): queryset.update(is_enable=False) -def enable_commentstatus(modeladmin, request, queryset): +def enable_commentstatus(queryset): queryset.update(is_enable=True) diff --git a/comments/migrations/0001_initial.py b/comments/migrations/0001_initial.py index 61d1e53..eec9566 100644 --- a/comments/migrations/0001_initial.py +++ b/comments/migrations/0001_initial.py @@ -1,9 +1,8 @@ # Generated by Django 4.1.7 on 2023-03-02 07:14 +import django.utils.timezone from django.conf import settings from django.db import migrations, models -import django.db.models.deletion -import django.utils.timezone class Migration(migrations.Migration): diff --git a/comments/migrations/0003_alter_comment_options_remove_comment_created_time_and_more.py b/comments/migrations/0003_alter_comment_options_remove_comment_created_time_and_more.py index a1ca970..6507ae1 100644 --- a/comments/migrations/0003_alter_comment_options_remove_comment_created_time_and_more.py +++ b/comments/migrations/0003_alter_comment_options_remove_comment_created_time_and_more.py @@ -1,9 +1,8 @@ # Generated by Django 4.2.5 on 2023-09-06 13:13 +import django.utils.timezone from django.conf import settings from django.db import migrations, models -import django.db.models.deletion -import django.utils.timezone class Migration(migrations.Migration): diff --git a/comments/tests.py b/comments/tests.py index 2a7f55f..32d872c 100644 --- a/comments/tests.py +++ b/comments/tests.py @@ -24,7 +24,8 @@ class CommentsTest(TransactionTestCase): username="liangliangyy1", password="liangliangyy1") - def update_article_comment_status(self, article): + @staticmethod + def update_article_comment_status(article): comments = article.comment_set.all() for comment in comments: comment.is_enable = True diff --git a/djangoblog/blog_signals.py b/djangoblog/blog_signals.py index 779a267..d331d76 100644 --- a/djangoblog/blog_signals.py +++ b/djangoblog/blog_signals.py @@ -45,7 +45,7 @@ send_email_signal = django.dispatch.Signal( @receiver(send_email_signal) -def send_email_signal_handler(sender, **kwargs): +def send_email_signal_handler(**kwargs): """`xjj` 发送邮件信号的处理函数 @@ -85,7 +85,7 @@ def send_email_signal_handler(sender, **kwargs): @receiver(oauth_user_login_signal) -def oauth_user_login_signal_handler(sender, **kwargs): +def oauth_user_login_signal_handler(**kwargs): """`xjj` OAuth 用户登录信号处理函数 @@ -109,13 +109,8 @@ def oauth_user_login_signal_handler(sender, **kwargs): @receiver(post_save) def model_post_save_callback( - sender, instance, - created, - raw, - using, - update_fields, - **kwargs): + update_fields): """`xjj` 模型保存后的回调函数,用于处理缓存清理和搜索引擎通知等操作 @@ -171,7 +166,7 @@ def model_post_save_callback( @receiver(user_logged_in) @receiver(user_logged_out) -def user_auth_callback(sender, request, user, **kwargs): +def user_auth_callback(user): if user and user.username: logger.info(user) delete_sidebar_cache() diff --git a/djangoblog/elasticsearch_backend.py b/djangoblog/elasticsearch_backend.py index f22ab2c..c049ad2 100644 --- a/djangoblog/elasticsearch_backend.py +++ b/djangoblog/elasticsearch_backend.py @@ -73,7 +73,8 @@ class ElasticSearchBackend(BaseSearchBackend): docs = self._get_models(models) self.manager.rebuild(docs) - def _delete(self, models): + @staticmethod + def _delete(models): """`xjj` 删除指定模型对象。 @@ -206,7 +207,8 @@ class ElasticSearchBackend(BaseSearchBackend): class ElasticSearchQuery(BaseSearchQuery): - def _convert_datetime(self, date): + @staticmethod + def _convert_datetime(date): """`xjj` 将日期时间对象转换为字符串格式 diff --git a/djangoblog/feeds.py b/djangoblog/feeds.py index cb5bcb3..18e2dbb 100644 --- a/djangoblog/feeds.py +++ b/djangoblog/feeds.py @@ -36,7 +36,8 @@ class DjangoBlogFeed(Feed): title = "且听风吟 大巧无工,重剑无锋. " link = "/feed/" - def author_name(self): + @staticmethod + def author_name(): """`xjj` 获取 RSS 订阅源的作者名称 @@ -46,7 +47,8 @@ class DjangoBlogFeed(Feed): """ return get_user_model().objects.first().nickname - def author_link(self): + @staticmethod + def author_link(): """`xjj` 获取 RSS 订阅源作者的链接地址 @@ -56,7 +58,8 @@ class DjangoBlogFeed(Feed): """ return get_user_model().objects.first().get_absolute_url() - def items(self): + @staticmethod + def items(): """`xjj` 获取 RSS 订阅源的文章列表 @@ -92,7 +95,8 @@ class DjangoBlogFeed(Feed): """ return CommonMarkdown.get_markdown(item.body) - def feed_copyright(self): + @staticmethod + def feed_copyright(): """`xjj` 获取 RSS 订阅源的版权信息 diff --git a/djangoblog/plugin_manage/base_plugin.py b/djangoblog/plugin_manage/base_plugin.py index df1ce0b..e7e1ed6 100644 --- a/djangoblog/plugin_manage/base_plugin.py +++ b/djangoblog/plugin_manage/base_plugin.py @@ -112,23 +112,28 @@ class BasePlugin: """渲染文章底部组件""" return None - def render_article_top_widget(self, context, **kwargs): + @staticmethod + def render_article_top_widget(): """渲染文章顶部组件""" return None - def render_header_widget(self, context, **kwargs): + @staticmethod + def render_header_widget(): """渲染页头组件""" return None - def render_footer_widget(self, context, **kwargs): + @staticmethod + def render_footer_widget(): """渲染页脚组件""" return None - def render_comment_before_widget(self, context, **kwargs): + @staticmethod + def render_comment_before_widget(): """渲染评论前组件""" return None - def render_comment_after_widget(self, context, **kwargs): + @staticmethod + def render_comment_after_widget(): """渲染评论后组件""" return None @@ -169,11 +174,13 @@ class BasePlugin: """获取插件JavaScript文件列表""" return [] - def get_head_html(self, context=None): + @staticmethod + def get_head_html(): """获取需要插入到中的HTML内容""" return "" - def get_body_html(self, context=None): + @staticmethod + def get_body_html(): """获取需要插入到底部的HTML内容""" return "" diff --git a/djangoblog/plugin_manage/loader.py b/djangoblog/plugin_manage/loader.py index ee750d0..096c1c1 100644 --- a/djangoblog/plugin_manage/loader.py +++ b/djangoblog/plugin_manage/loader.py @@ -1,5 +1,6 @@ -import os import logging +import os + from django.conf import settings logger = logging.getLogger(__name__) diff --git a/djangoblog/sitemap.py b/djangoblog/sitemap.py index 4fc8b78..80dd4a8 100644 --- a/djangoblog/sitemap.py +++ b/djangoblog/sitemap.py @@ -82,7 +82,8 @@ class ArticleSiteMap(Sitemap): """ return Article.objects.filter(status='p') - def lastmod(self, obj): + @staticmethod + def lastmod(obj): """`xjj` 获取指定文章对象的最后修改时间 @@ -117,7 +118,8 @@ class CategorySiteMap(Sitemap): """ return Category.objects.all() - def lastmod(self, obj): + @staticmethod + def lastmod(obj): """`xjj` 获取分类对象的最后修改时间 @@ -152,7 +154,8 @@ class TagSiteMap(Sitemap): """ return Tag.objects.all() - def lastmod(self, obj): + @staticmethod + def lastmod(obj): """`xjj` 获取指定标签对象的最后修改时间 @@ -190,7 +193,8 @@ class UserSiteMap(Sitemap): """ return list(set(map(lambda x: x.author, Article.objects.all()))) - def lastmod(self, obj): + @staticmethod + def lastmod(obj): """`xjj` 获取指定用户对象的最后修改时间 diff --git a/djangoblog/spider_notify.py b/djangoblog/spider_notify.py index bfe1d09..1032ff3 100644 --- a/djangoblog/spider_notify.py +++ b/djangoblog/spider_notify.py @@ -26,7 +26,7 @@ from django.conf import settings logger = logging.getLogger(__name__) -class SpiderNotify(): +class SpiderNotify: """`xjj` 爬虫通知类,用于向搜索引擎提交 URL 通知 diff --git a/djangoblog/urls.py b/djangoblog/urls.py index 6a9e1de..11474cf 100644 --- a/djangoblog/urls.py +++ b/djangoblog/urls.py @@ -13,15 +13,16 @@ Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ +import time + from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib.sitemaps.views import sitemap +from django.http import JsonResponse from django.urls import path, include from django.urls import re_path from haystack.views import search_view_factory -from django.http import JsonResponse -import time from blog.views import EsSearchView from djangoblog.admin_site import admin_site @@ -43,7 +44,7 @@ handler500 = 'blog.views.server_error_view' handle403 = 'blog.views.permission_denied_view' -def health_check(request): +def health_check(): """ 健康检查接口 简单返回服务健康状态 diff --git a/djangoblog/utils.py b/djangoblog/utils.py index 045264e..1294385 100644 --- a/djangoblog/utils.py +++ b/djangoblog/utils.py @@ -52,7 +52,7 @@ def get_max_articleid_commentid(): """ from blog.models import Article from comments.models import Comment - return (Article.objects.latest().pk, Comment.objects.latest().pk) + return Article.objects.latest().pk, Comment.objects.latest().pk def get_sha256(str): @@ -138,14 +138,14 @@ def cache_decorator(expiration=3 * 60): def expire_view_cache(path, servername, serverport, key_prefix=None): - ''' + """ 刷新视图缓存 :param path:url路径 :param servername:host :param serverport:端口 :param key_prefix:前缀 :return:是否成功 - ''' + """ from django.http import HttpRequest from django.utils.cache import get_cache_key @@ -332,11 +332,11 @@ def get_blog_setting(): def save_user_avatar(url): - ''' + """ 保存用户头像 :param url:头像url :return: 本地路径 - ''' + """ logger.info(url) try: @@ -418,7 +418,7 @@ ALLOWED_CLASSES = [ 's1', 'ss', 'bp', 'vc', 'vg', 'vi', 'il' ] -def class_filter(tag, name, value): +def class_filter(name, value): """`xjj` 自定义 class 属性过滤器 diff --git a/djangoblog/whoosh_cn_backend.py b/djangoblog/whoosh_cn_backend.py index ac6cd4e..7d75681 100644 --- a/djangoblog/whoosh_cn_backend.py +++ b/djangoblog/whoosh_cn_backend.py @@ -29,11 +29,11 @@ import re import shutil import threading import warnings +from datetime import datetime import six from django.conf import settings from django.core.exceptions import ImproperlyConfigured -from datetime import datetime from django.utils.encoding import force_str from haystack.backends import BaseEngine, BaseSearchBackend, BaseSearchQuery, EmptyResults, log_query from haystack.constants import DJANGO_CT, DJANGO_ID, ID @@ -155,7 +155,7 @@ class WhooshSearchBackend(BaseSearchBackend): connections[self.connection_alias].get_unified_index().all_searchfields()) self.parser = QueryParser(self.content_field_name, schema=self.schema) - if new_index is True: + if new_index: self.index = self.storage.create_index(self.schema) else: try: @@ -230,7 +230,7 @@ class WhooshSearchBackend(BaseSearchBackend): raise SearchBackendError( "No fields were found in any search_indexes. Please correct this before attempting to search.") - return (content_field_name, Schema(**schema_fields)) + return content_field_name, Schema(**schema_fields) def update(self, index, iterable, commit=True): """`xjj` @@ -389,7 +389,8 @@ class WhooshSearchBackend(BaseSearchBackend): self.index = self.index.refresh() self.index.optimize() - def calculate_page(self, start_offset=0, end_offset=None): + @staticmethod + def calculate_page(start_offset=0, end_offset=None): """`xjj` 根据偏移量计算分页信息。 @@ -698,7 +699,7 @@ class WhooshSearchBackend(BaseSearchBackend): # Deferred models will have a different class ("RealClass_Deferred_fieldname") # which won't be in our registry: - model_klass = model_instance._meta.concrete_model + model_instance._meta.concrete_model field_name = self.content_field_name narrow_queries = set() @@ -943,7 +944,8 @@ class WhooshSearchBackend(BaseSearchBackend): spelling_suggestion = ' '.join(suggested_words) return spelling_suggestion - def _from_python(self, value): + @staticmethod + def _from_python(value): """ Converts Python values to a string for Whoosh. @@ -966,7 +968,8 @@ class WhooshSearchBackend(BaseSearchBackend): value = force_str(value) return value - def _to_python(self, value): + @staticmethod + def _to_python(value): """ Converts values from Whoosh to native Python values. @@ -1018,7 +1021,8 @@ class WhooshSearchBackend(BaseSearchBackend): class WhooshSearchQuery(BaseSearchQuery): - def _convert_datetime(self, date): + @staticmethod + def _convert_datetime(date): """`xjj` 将日期时间对象转换为 Whoosh 可识别的字符串格式。 @@ -1075,7 +1079,7 @@ class WhooshSearchQuery(BaseSearchQuery): str: 构建好的查询片段字符串。 """ from haystack import connections - query_frag = '' + '' is_datetime = False if not hasattr(value, 'input_type_name'): @@ -1120,7 +1124,7 @@ class WhooshSearchQuery(BaseSearchQuery): 'fuzzy': u'%s~', } - if value.post_process is False: + if not value.post_process: query_frag = prepared_value else: if filter_type in [ @@ -1139,7 +1143,7 @@ class WhooshSearchQuery(BaseSearchQuery): if isinstance(prepared_value, six.string_types): possible_values = prepared_value.split(' ') else: - if is_datetime is True: + if is_datetime: prepared_value = self._convert_datetime( prepared_value) @@ -1165,7 +1169,7 @@ class WhooshSearchQuery(BaseSearchQuery): pv = self.backend._from_python(possible_value) - if is_datetime is True: + if is_datetime: pv = self._convert_datetime(pv) if isinstance(pv, six.string_types) and not is_datetime: @@ -1192,7 +1196,7 @@ class WhooshSearchQuery(BaseSearchQuery): prepared_value = Exact(prepared_value).prepare(self) query_frag = filter_types[filter_type] % prepared_value else: - if is_datetime is True: + if is_datetime: prepared_value = self._convert_datetime(prepared_value) query_frag = filter_types[filter_type] % prepared_value diff --git a/oauth/admin.py b/oauth/admin.py index 57eab5f..9c1a275 100644 --- a/oauth/admin.py +++ b/oauth/admin.py @@ -38,12 +38,13 @@ class OAuthUserAdmin(admin.ModelAdmin): return format_html( u'%s' % (link, obj.author.nickname if obj.author.nickname else obj.author.email)) + return None def show_user_image(self, obj): img = obj.picture return format_html( u'' % - (img)) + img) link_to_usermodel.short_description = '用户' show_user_image.short_description = '用户头像' diff --git a/oauth/migrations/0001_initial.py b/oauth/migrations/0001_initial.py index 3aa3e03..3497554 100644 --- a/oauth/migrations/0001_initial.py +++ b/oauth/migrations/0001_initial.py @@ -1,9 +1,8 @@ # Generated by Django 4.1.7 on 2023-03-07 09:53 +import django.utils.timezone from django.conf import settings from django.db import migrations, models -import django.db.models.deletion -import django.utils.timezone class Migration(migrations.Migration): diff --git a/oauth/migrations/0002_alter_oauthconfig_options_alter_oauthuser_options_and_more.py b/oauth/migrations/0002_alter_oauthconfig_options_alter_oauthuser_options_and_more.py index d5cc70e..ba857da 100644 --- a/oauth/migrations/0002_alter_oauthconfig_options_alter_oauthuser_options_and_more.py +++ b/oauth/migrations/0002_alter_oauthconfig_options_alter_oauthuser_options_and_more.py @@ -1,9 +1,8 @@ # Generated by Django 4.2.5 on 2023-09-06 13:13 +import django.utils.timezone from django.conf import settings from django.db import migrations, models -import django.db.models.deletion -import django.utils.timezone class Migration(migrations.Migration): diff --git a/oauth/oauthmanager.py b/oauth/oauthmanager.py index 2e7ceef..a50a51a 100644 --- a/oauth/oauthmanager.py +++ b/oauth/oauthmanager.py @@ -13,9 +13,9 @@ logger = logging.getLogger(__name__) class OAuthAccessTokenException(Exception): - ''' + """ oauth授权失败异常 - ''' + """ class BaseOauthManager(metaclass=ABCMeta): @@ -56,12 +56,14 @@ class BaseOauthManager(metaclass=ABCMeta): def get_picture(self, metadata): pass - def do_get(self, url, params, headers=None): + @staticmethod + def do_get(url, params, headers=None): rsp = requests.get(url=url, params=params, headers=headers) logger.info(rsp.text) return rsp.text - def do_post(self, url, params, headers=None): + @staticmethod + def do_post(url, params, headers=None): rsp = requests.post(url, params, headers=headers) logger.info(rsp.text) return rsp.text @@ -434,6 +436,7 @@ class QQOauthManager(BaseOauthManager): token = d['access_token'] self.access_token = token[0] return token + return None else: raise OAuthAccessTokenException(rsp) @@ -452,6 +455,7 @@ class QQOauthManager(BaseOauthManager): openid = str(obj['openid']) self.openid = openid return openid + return None def get_oauth_userinfo(self): openid = self.get_open_id() @@ -475,6 +479,7 @@ class QQOauthManager(BaseOauthManager): if 'figureurl' in obj: user.picture = str(obj['figureurl']) return user + return None def get_picture(self, metadata): datas = json.loads(metadata) diff --git a/oauth/tests.py b/oauth/tests.py index bb23b9b..da5f502 100644 --- a/oauth/tests.py +++ b/oauth/tests.py @@ -39,7 +39,8 @@ class OauthLoginTest(TestCase): self.factory = RequestFactory() self.apps = self.init_apps() - def init_apps(self): + @staticmethod + def init_apps(): applications = [p() for p in BaseOauthManager.__subclasses__()] for application in applications: c = OAuthConfig() @@ -53,13 +54,14 @@ class OauthLoginTest(TestCase): for app in self.apps: if app.ICON_NAME.lower() == type: return app + return None @patch("oauth.oauthmanager.WBOauthManager.do_post") @patch("oauth.oauthmanager.WBOauthManager.do_get") def test_weibo_login(self, mock_do_get, mock_do_post): weibo_app = self.get_app_by_type('weibo') assert weibo_app - url = weibo_app.get_authorization_url() + weibo_app.get_authorization_url() mock_do_post.return_value = json.dumps({"access_token": "access_token", "uid": "uid" }) @@ -78,7 +80,7 @@ class OauthLoginTest(TestCase): def test_google_login(self, mock_do_get, mock_do_post): google_app = self.get_app_by_type('google') assert google_app - url = google_app.get_authorization_url() + google_app.get_authorization_url() mock_do_post.return_value = json.dumps({ "access_token": "access_token", "id_token": "id_token", @@ -89,7 +91,7 @@ class OauthLoginTest(TestCase): "sub": "sub", "email": "email", }) - token = google_app.get_access_token_by_code('code') + google_app.get_access_token_by_code('code') userinfo = google_app.get_oauth_userinfo() self.assertEqual(userinfo.token, 'access_token') self.assertEqual(userinfo.openid, 'sub') @@ -109,7 +111,7 @@ class OauthLoginTest(TestCase): "id": "id", "email": "email", }) - token = github_app.get_access_token_by_code('code') + github_app.get_access_token_by_code('code') userinfo = github_app.get_oauth_userinfo() self.assertEqual(userinfo.token, 'gho_16C7e42F292c6912E7710c838347Ae178B4a') self.assertEqual(userinfo.openid, 'id') @@ -134,7 +136,7 @@ class OauthLoginTest(TestCase): } } }) - token = facebook_app.get_access_token_by_code('code') + facebook_app.get_access_token_by_code('code') userinfo = facebook_app.get_oauth_userinfo() self.assertEqual(userinfo.token, 'access_token') @@ -148,12 +150,12 @@ class OauthLoginTest(TestCase): "openid": "openid", }) ]) - def test_qq_login(self, mock_do_get): + def test_qq_login(self): qq_app = self.get_app_by_type('qq') assert qq_app url = qq_app.get_authorization_url() self.assertTrue("qq.com" in url) - token = qq_app.get_access_token_by_code('code') + qq_app.get_access_token_by_code('code') userinfo = qq_app.get_oauth_userinfo() self.assertEqual(userinfo.token, 'access_token') diff --git a/owntracks/migrations/0001_initial.py b/owntracks/migrations/0001_initial.py index 9eee55c..19bfec2 100644 --- a/owntracks/migrations/0001_initial.py +++ b/owntracks/migrations/0001_initial.py @@ -1,7 +1,7 @@ # Generated by Django 4.1.7 on 2023-03-02 07:14 -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/owntracks/tests.py b/owntracks/tests.py index 3b4b9d8..6c12be6 100644 --- a/owntracks/tests.py +++ b/owntracks/tests.py @@ -42,7 +42,7 @@ class OwnTrackLogTest(TestCase): rsp = self.client.get('/owntracks/show_maps') self.assertEqual(rsp.status_code, 302) - user = BlogUser.objects.create_superuser( + BlogUser.objects.create_superuser( email="liangliangyy1@gmail.com", username="liangliangyy1", password="liangliangyy1") diff --git a/plugins/article_copyright/plugin.py b/plugins/article_copyright/plugin.py index 5dba3b3..a51f128 100644 --- a/plugins/article_copyright/plugin.py +++ b/plugins/article_copyright/plugin.py @@ -1,5 +1,5 @@ -from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME @@ -14,7 +14,8 @@ class ArticleCopyrightPlugin(BasePlugin): # 在这里将插件的方法注册到指定的钩子上 hooks.register(ARTICLE_CONTENT_HOOK_NAME, self.add_copyright_to_content) - def add_copyright_to_content(self, content, *args, **kwargs): + @staticmethod + def add_copyright_to_content(content, **kwargs): """ 这个方法会被注册到 'the_content' 过滤器钩子上。 它接收原始内容,并返回添加了版权信息的新内容。 diff --git a/plugins/article_recommendation/plugin.py b/plugins/article_recommendation/plugin.py index 6656a07..05c4bb9 100644 --- a/plugins/article_recommendation/plugin.py +++ b/plugins/article_recommendation/plugin.py @@ -1,8 +1,9 @@ import logging -from djangoblog.plugin_manage.base_plugin import BasePlugin + +from blog.models import Article from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage.hook_constants import ARTICLE_DETAIL_LOAD -from blog.models import Article logger = logging.getLogger(__name__) @@ -33,7 +34,7 @@ class ArticleRecommendationPlugin(BasePlugin): """注册钩子""" hooks.register(ARTICLE_DETAIL_LOAD, self.on_article_detail_load) - def on_article_detail_load(self, article, context, request, *args, **kwargs): + def on_article_detail_load(self, article, context): """文章详情页加载时的处理""" # 可以在这里预加载推荐数据到context中 recommendations = self.get_recommendations(article) @@ -194,7 +195,8 @@ class ArticleRecommendationPlugin(BasePlugin): return valid_recommendations[:count] - def get_popular_articles(self, count=3): + @staticmethod + def get_popular_articles(count=3): """获取热门文章""" return list(Article.objects.filter( status='p' diff --git a/plugins/external_links/plugin.py b/plugins/external_links/plugin.py index 5b2ef14..35456b3 100644 --- a/plugins/external_links/plugin.py +++ b/plugins/external_links/plugin.py @@ -1,7 +1,8 @@ import re from urllib.parse import urlparse -from djangoblog.plugin_manage.base_plugin import BasePlugin + from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME @@ -14,7 +15,8 @@ class ExternalLinksPlugin(BasePlugin): def register_hooks(self): hooks.register(ARTICLE_CONTENT_HOOK_NAME, self.process_external_links) - def process_external_links(self, content, *args, **kwargs): + @staticmethod + def process_external_links(content): from djangoblog.utils import get_current_site site_domain = get_current_site().domain diff --git a/plugins/image_lazy_loading/plugin.py b/plugins/image_lazy_loading/plugin.py index b4b9e0a..3c66728 100644 --- a/plugins/image_lazy_loading/plugin.py +++ b/plugins/image_lazy_loading/plugin.py @@ -1,8 +1,9 @@ -import re import hashlib +import re from urllib.parse import urlparse -from djangoblog.plugin_manage.base_plugin import BasePlugin + from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME @@ -27,7 +28,7 @@ class ImageOptimizationPlugin(BasePlugin): def register_hooks(self): hooks.register(ARTICLE_CONTENT_HOOK_NAME, self.optimize_images) - def optimize_images(self, content, *args, **kwargs): + def optimize_images(self, content): """ 优化文章中的图片标签 """ @@ -63,7 +64,8 @@ class ImageOptimizationPlugin(BasePlugin): return optimized_content - def _parse_img_attributes(self, attr_string): + @staticmethod + def _parse_img_attributes(attr_string): """ 解析 img 标签的属性 """ @@ -150,7 +152,8 @@ class ImageOptimizationPlugin(BasePlugin): return attrs - def _build_img_tag(self, attrs): + @staticmethod + def _build_img_tag(attrs): """ 重新构建 img 标签 """ @@ -167,7 +170,8 @@ class ImageOptimizationPlugin(BasePlugin): return f'' - def _get_current_domain(self): + @staticmethod + def _get_current_domain(): """ 获取当前网站域名 """ diff --git a/plugins/reading_time/plugin.py b/plugins/reading_time/plugin.py index 4b929d8..4d3a6ad 100644 --- a/plugins/reading_time/plugin.py +++ b/plugins/reading_time/plugin.py @@ -1,7 +1,8 @@ import math import re -from djangoblog.plugin_manage.base_plugin import BasePlugin + from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME @@ -14,7 +15,8 @@ class ReadingTimePlugin(BasePlugin): def register_hooks(self): hooks.register(ARTICLE_CONTENT_HOOK_NAME, self.add_reading_time) - def add_reading_time(self, content, *args, **kwargs): + @staticmethod + def add_reading_time(content, **kwargs): """ 计算阅读时间并添加到内容开头。 只在文章详情页显示,首页(文章列表页)不显示。 diff --git a/plugins/seo_optimizer/plugin.py b/plugins/seo_optimizer/plugin.py index de12c15..c3df658 100644 --- a/plugins/seo_optimizer/plugin.py +++ b/plugins/seo_optimizer/plugin.py @@ -1,9 +1,10 @@ import json + from django.utils.html import strip_tags -from django.template.defaultfilters import truncatewords -from djangoblog.plugin_manage.base_plugin import BasePlugin + +from blog.models import Article, Category from djangoblog.plugin_manage import hooks -from blog.models import Article, Category, Tag +from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.utils import get_blog_setting @@ -16,7 +17,8 @@ class SeoOptimizerPlugin(BasePlugin): def register_hooks(self): hooks.register('head_meta', self.dispatch_seo_generation) - def _get_article_seo_data(self, context, request, blog_setting): + @staticmethod + def _get_article_seo_data(context, request, blog_setting): article = context.get('article') if not isinstance(article, Article): return None @@ -61,7 +63,8 @@ class SeoOptimizerPlugin(BasePlugin): "json_ld": structured_data } - def _get_category_seo_data(self, context, request, blog_setting): + @staticmethod + def _get_category_seo_data(context, request, blog_setting): category_name = context.get('tag_name') if not category_name: return None @@ -92,7 +95,8 @@ class SeoOptimizerPlugin(BasePlugin): "json_ld": structured_data } - def _get_default_seo_data(self, context, request, blog_setting): + @staticmethod + def _get_default_seo_data(request, blog_setting): # Homepage and other default pages structured_data = { "@context": "https://schema.org", @@ -129,7 +133,7 @@ class SeoOptimizerPlugin(BasePlugin): seo_data = self._get_category_seo_data(context, request, blog_setting) if not seo_data: - seo_data = self._get_default_seo_data(context, request, blog_setting) + seo_data = self._get_default_seo_data(request, blog_setting) json_ld_script = f'' diff --git a/plugins/view_count/plugin.py b/plugins/view_count/plugin.py index 15e9d94..5d02b4f 100644 --- a/plugins/view_count/plugin.py +++ b/plugins/view_count/plugin.py @@ -1,5 +1,5 @@ -from djangoblog.plugin_manage.base_plugin import BasePlugin from djangoblog.plugin_manage import hooks +from djangoblog.plugin_manage.base_plugin import BasePlugin class ViewCountPlugin(BasePlugin): @@ -11,7 +11,8 @@ class ViewCountPlugin(BasePlugin): def register_hooks(self): hooks.register('after_article_body_get', self.record_view) - def record_view(self, article, *args, **kwargs): + @staticmethod + def record_view(article): article.viewed() diff --git a/servermanager/api/blogapi.py b/servermanager/api/blogapi.py index 8a4d6ac..5fe3249 100644 --- a/servermanager/api/blogapi.py +++ b/servermanager/api/blogapi.py @@ -14,7 +14,8 @@ class BlogApi: sqs = sqs.load_all() return sqs[:self.__max_takecount__] - def get_category_lists(self): + @staticmethod + def get_category_lists(): return Category.objects.all() def get_category_articles(self, categoryname): diff --git a/servermanager/api/commonapi.py b/servermanager/api/commonapi.py index 83ad9ff..ccc9de4 100644 --- a/servermanager/api/commonapi.py +++ b/servermanager/api/commonapi.py @@ -44,7 +44,8 @@ class CommandHandler: else: return "未找到相关命令,请输入hepme获得帮助。" - def __run_command__(self, cmd): + @staticmethod + def __run_command__(cmd): try: res = os.popen(cmd).read() return res diff --git a/servermanager/robot.py b/servermanager/robot.py index 7b45736..6801bc6 100644 --- a/servermanager/robot.py +++ b/servermanager/robot.py @@ -47,7 +47,7 @@ def convert_to_article_reply(articles, message): @robot.filter(re.compile(r"^\?.*")) -def search(message, session): +def search(message): s = message.content searchstr = str(s).replace('?', '') result = blogapi.search_articles(searchstr) @@ -60,14 +60,14 @@ def search(message, session): @robot.filter(re.compile(r'^category\s*$', re.I)) -def category(message, session): +def category(): categorys = blogapi.get_category_lists() content = ','.join(map(lambda x: x.name, categorys)) return '所有文章分类目录:' + content @robot.filter(re.compile(r'^recent\s*$', re.I)) -def recents(message, session): +def recents(message): articles = blogapi.get_recent_articles() if articles: reply = convert_to_article_reply(articles, message) @@ -77,7 +77,7 @@ def recents(message, session): @robot.filter(re.compile('^help$', re.I)) -def help(message, session): +def help(): return '''欢迎关注! 默认会与图灵机器人聊天~~ 你可以通过下面这些命令来获得信息 @@ -99,12 +99,12 @@ def help(message, session): @robot.filter(re.compile(r'^weather\:.*$', re.I)) -def weather(message, session): +def weather(): return "建设中..." @robot.filter(re.compile(r'^idcard\:.*$', re.I)) -def idcard(message, session): +def idcard(): return "建设中..." @@ -123,7 +123,7 @@ class MessageHandler: try: info = session[userid] self.userinfo = jsonpickle.decode(info) - except Exception as e: + except Exception: userinfo = WxUserInfo() self.userinfo = userinfo @@ -179,7 +179,7 @@ class MessageHandler: return ChatGPT.chat(info) -class WxUserInfo(): +class WxUserInfo: def __init__(self): self.isAdmin = False self.isPasswordSet = False diff --git a/servermanager/tests.py b/servermanager/tests.py index 22a6689..fb856c4 100644 --- a/servermanager/tests.py +++ b/servermanager/tests.py @@ -1,5 +1,4 @@ from django.test import Client, RequestFactory, TestCase -from django.utils import timezone from werobot.messages.messages import TextMessage from accounts.models import BlogUser @@ -42,10 +41,10 @@ class ServerManagerTest(TestCase): article.save() s = TextMessage([]) s.content = "nice" - rsp = search(s, None) - rsp = category(None, None) + search(s) + rsp = category() self.assertIsNotNone(rsp) - rsp = recents(None, None) + rsp = recents(None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands()