搭建自己的博客(十六):封装优化阅读量代码

1、将阅读量的代码封装在一个app中,增加扩展性

新建app:

python manage.py startapp read_statistics

2、变化的部分

3、上代码

from django.contrib import admin
from .models import BlogType, Blog

# Register your models here.

@admin.register(BlogType)
class BlogTypeAdmin(admin.ModelAdmin):
    list_display = (‘id‘, ‘type_name‘)  # 需要显示的列表

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    list_display = (‘title‘, ‘blog_type‘, ‘author‘, ‘get_read_num‘, ‘created_time‘, ‘last_updated_time‘)

blog下的admin.py

from django.db import models
from django.contrib.auth.models import User
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.contenttypes.models import ContentType
from read_statistics.models import ReadNum, ReadNumExpandMethod

# Create your models here.

# 博客分类
class BlogType(models.Model):
    type_name = models.CharField(max_length=15)  # 博客分类名称

    def __str__(self):  # 显示标签名
        return self.type_name

# 博客
class Blog(models.Model, ReadNumExpandMethod):
    title = models.CharField(max_length=50)  # 博客标题
    blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING)  # 博客分类
    content = RichTextUploadingField()  # 博客内容,使用富文本编辑
    author = models.ForeignKey(User, on_delete=models.DO_NOTHING)  # 博客作者
    created_time = models.DateTimeField(auto_now_add=True)  # 博客创建时间
    last_updated_time = models.DateTimeField(auto_now=True)  # 博客更新事件

    def __str__(self):  # 显示标题名
        return "<Blog:{}>".format(self.title)

    class Meta:
        ordering = [‘-created_time‘]  # 定义排序规则,按照创建时间倒序

blog下的models.py

from django.shortcuts import render_to_response, get_object_or_404
from .models import Blog, BlogType
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count
from read_statistics.utils import read_statistics_once_read

# 分页部分公共代码
def blog_list_common_data(requests, blogs_all_list):
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一个参数是全部内容,第二个是每页多少
    page_num = requests.GET.get(‘page‘, 1)  # 获取url的页面参数(get请求)
    page_of_blogs = paginator.get_page(page_num)  # 从分页器中获取指定页码的内容

    current_page_num = page_of_blogs.number  # 获取当前页
    all_pages = paginator.num_pages
    if all_pages < 5:
        page_range = list(
            range(max(current_page_num - 2, 1),
                  min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码
    else:
        if current_page_num <= 2:
            page_range = range(1, 5 + 1)
        elif current_page_num >= all_pages - 2:
            page_range = range(all_pages - 4, paginator.num_pages + 1)
        else:
            page_range = list(
                range(max(current_page_num - 2, 1),
                      min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码

    blog_dates = Blog.objects.dates(‘created_time‘, ‘month‘, order=‘DESC‘)
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year, created_time__month=blog_date.month).count()
        blog_dates_dict = {
            blog_date: blog_count
        }

    return {
        ‘blogs‘: page_of_blogs.object_list,
        ‘page_of_blogs‘: page_of_blogs,
        ‘blog_types‘: BlogType.objects.annotate(blog_count=Count(‘blog‘)),  # 添加查询并添加字段
        ‘page_range‘: page_range,
        ‘blog_dates‘: blog_dates_dict
    }

# 博客列表
def blog_list(requests):
    blogs_all_list = Blog.objects.all()  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    return render_to_response(‘blog/blog_list.html‘, context)

# 根据类型筛选
def blogs_with_type(requests, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    context[‘blog_type‘] = blog_type
    return render_to_response(‘blog/blog_with_type.html‘, context)

# 根据日期筛选
def blogs_with_date(requests, year, month):
    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    context[‘blogs_with_date‘] = ‘{}年{}日‘.format(year, month)
    return render_to_response(‘blog/blog_with_date.html‘, context)

# 博客详情
def blog_detail(requests, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    obj_key = read_statistics_once_read(requests, blog)

    context = {
        ‘blog‘: blog,
        ‘previous_blog‘: Blog.objects.filter(created_time__gt=blog.created_time).last(),
        ‘next_blog‘: Blog.objects.filter(created_time__lt=blog.created_time).first(),
    }
    response = render_to_response(‘blog/blog_detail.html‘, context)
    response.set_cookie(obj_key, ‘true‘)

    return response

blog下的views.py

"""
Django settings for myblog project.

Generated by ‘django-admin startproject‘ using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘ea+kzo_5k^[email protected]([email protected]*+w5d11=0mp1p5ngr‘

# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘ckeditor‘,
    ‘ckeditor_uploader‘,
    ‘blog.apps.BlogConfig‘,  # 将自己创建的app添加到设置中
    ‘read_statistics.apps.ReadStatisticsConfig‘,  # 注册阅读统计app

]

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
    ‘blog.middleware.mymiddleware.My404‘,  # 添加自己的中间件
]

ROOT_URLCONF = ‘myblog.urls‘

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [
            os.path.join(BASE_DIR, ‘templates‘),
        ],
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]

WSGI_APPLICATION = ‘myblog.wsgi.application‘

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    # ‘default‘: {
    #     ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
    #     ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    # }
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘myblogs‘,  # 要连接的数据库,连接前需要创建好
        ‘USER‘: ‘root‘,  # 连接数据库的用户名
        ‘PASSWORD‘: ‘felixwang‘,  # 连接数据库的密码
        ‘HOST‘: ‘127.0.0.1‘,  # 连接主机,默认本级
        ‘PORT‘: 3306  # 端口 默认3306
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.MinimumLengthValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.CommonPasswordValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.NumericPasswordValidator‘,
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

# LANGUAGE_CODE = ‘en-us‘
# 语言
LANGUAGE_CODE = ‘zh-hans‘

# TIME_ZONE = ‘UTC‘
# 时区
TIME_ZONE = ‘Asia/Shanghai‘

USE_I18N = True

USE_L10N = True

# 不考虑时区
USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = ‘/static/‘
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

# media
MEDIA_URL = ‘/media/‘
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media‘)

# 配置ckeditor
CKEDITOR_UPLOAD_PATH = ‘upload/‘

# 自定义参数
EACH_PAGE_BLOGS_NUMBER = 7

settings.py

from django.contrib import admin
from .models import ReadNum

# Register your models here.

@admin.register(ReadNum)
class ReadNumAdmin(admin.ModelAdmin):
    list_display = (‘read_num‘, ‘content_object‘)

read_statistics下的admin.py

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db.models.fields import exceptions

# Create your models here.

# 使用到了contenttype 参考网址:https://docs.djangoproject.com/en/2.1/ref/contrib/contenttypes/
class ReadNum(models.Model):
    read_num = models.IntegerField(default=0)  # 阅读量
    content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey(‘content_type‘, ‘object_id‘)

    def __str__(self):
        return str(self.read_num)

# 阅读计数扩展方法
class ReadNumExpandMethod:
    def get_read_num(self):  # 获取一对一关联的阅读数
        try:
            ct = ContentType.objects.get_for_model(self)
            readnum = ReadNum.objects.get(content_type=ct, object_id=self.pk)
            return readnum.read_num
        except exceptions.ObjectDoesNotExist as e:
            return 0

read_statistics下的models.py

# -*- coding: utf-8 -*-
# @Time    : 18-11-17 下午10:03
# @Author  : Felix Wang
from django.contrib.contenttypes.models import ContentType
from read_statistics.models import ReadNum

def read_statistics_once_read(requests, obj):
    ct = ContentType.objects.get_for_model(obj)
    key = ‘{}_{}_read‘.format(ct.model, obj.pk)

    # 获取并处理阅读计数
    if not requests.COOKIES.get(key):
        if ReadNum.objects.filter(content_type=ct, object_id=obj.pk).count():
            readnum = ReadNum.objects.get(content_type=ct, object_id=obj.pk)
        else:
            readnum = ReadNum(content_type=ct, object_id=obj.pk)
        # 处理阅读量
        readnum.read_num += 1
        readnum.save()
    return key

read_statistics下的utils.py

4、封装和优化了之前的代码

from django.shortcuts import render_to_response, get_object_or_404from .models import Blog, BlogTypefrom django.core.paginator import Paginatorfrom django.conf import settingsfrom django.db.models import Countfrom read_statistics.utils import read_statistics_once_read

# 分页部分公共代码def blog_list_common_data(requests, blogs_all_list):    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一个参数是全部内容,第二个是每页多少page_num = requests.GET.get(‘page‘, 1)  # 获取url的页面参数(get请求)page_of_blogs = paginator.get_page(page_num)  # 从分页器中获取指定页码的内容

current_page_num = page_of_blogs.number  # 获取当前页all_pages = paginator.num_pages    if all_pages < 5:        page_range = list(            range(max(current_page_num - 2, 1),min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码else:        if current_page_num <= 2:            page_range = range(1, 5 + 1)        elif current_page_num >= all_pages - 2:            page_range = range(all_pages - 4, paginator.num_pages + 1)        else:            page_range = list(                range(max(current_page_num - 2, 1),min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码

blog_dates = Blog.objects.dates(‘created_time‘, ‘month‘, order=‘DESC‘)    blog_dates_dict = {}    for blog_date in blog_dates:        blog_count = Blog.objects.filter(created_time__year=blog_date.year, created_time__month=blog_date.month).count()        blog_dates_dict = {            blog_date: blog_count        }

    return {        ‘blogs‘: page_of_blogs.object_list,‘page_of_blogs‘: page_of_blogs,‘blog_types‘: BlogType.objects.annotate(blog_count=Count(‘blog‘)),  # 添加查询并添加字段‘page_range‘: page_range,‘blog_dates‘: blog_dates_dict    }

# 博客列表def blog_list(requests):    blogs_all_list = Blog.objects.all()  # 获取全部博客context = blog_list_common_data(requests, blogs_all_list)    return render_to_response(‘blog/blog_list.html‘, context)

# 根据类型筛选def blogs_with_type(requests, blog_type_pk):    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)    blogs_all_list = Blog.objects.filter(blog_type=blog_type)  # 获取全部博客context = blog_list_common_data(requests, blogs_all_list)    context[‘blog_type‘] = blog_type    return render_to_response(‘blog/blog_with_type.html‘, context)

# 根据日期筛选def blogs_with_date(requests, year, month):    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 获取全部博客context = blog_list_common_data(requests, blogs_all_list)    context[‘blogs_with_date‘] = ‘{}年{}日‘.format(year, month)    return render_to_response(‘blog/blog_with_date.html‘, context)

# 博客详情def blog_detail(requests, blog_pk):    blog = get_object_or_404(Blog, pk=blog_pk)    obj_key = read_statistics_once_read(requests, blog)

    context = {        ‘blog‘: blog,‘previous_blog‘: Blog.objects.filter(created_time__gt=blog.created_time).last(),‘next_blog‘: Blog.objects.filter(created_time__lt=blog.created_time).first(),}    response = render_to_response(‘blog/blog_detail.html‘, context)    response.set_cookie(obj_key, ‘true‘)

    return response

原文地址:https://www.cnblogs.com/felixwang2/p/9976094.html

时间: 2024-10-12 21:07:18

搭建自己的博客(十六):封装优化阅读量代码的相关文章

github+hexo搭建自己的博客网站(六)进阶配置(搜索引擎收录,优化你的url)

详细的可以查看hexo博客的演示:https://saucxs.github.io/ 绑定了域名: http://www.chengxinsong.cn hexo+github博客网站源码(可以clone,运行,看到博客演示.觉得可以给颗星星):https://github.com/saucxs/hexo-blog-origin.git 一.搜索引擎收录 1.验证网站所有权 登录百度站长平台:http://zhanzhang.baidu.com,只要有百度旗下的账号就可以登录,登录成功之后在站点

2015年12月12 Node.js实战(一)使用Express+MongoDB搭建多人博客

序,Node是基于V8引擎的服务器端脚本语言. 基础准备 Node.js: Express:本文用的是3.21.2版本,目前最新版本为4.13.3,Express4和Express3还是有较大区别,可以去官网查看wiki:https://github.com/strongloop/express MongoDB: 一.使用Express搭建一个站点 1 快速开始安装Express Express是Node上最流行的Web开发框架,通过它可以快速开发一个Web应用.全局模式下输入命令: $ npm

github+hexo搭建自己的博客网站(七)注意事项(避免read.me,CNAME文件的覆盖,手动改github page的域名)

详细的可以查看hexo博客的演示:https://saucxs.github.io/ 绑定域名可以查看:http://www.chengxinsong.cn 可以查看在github上生成的静态文件(如果觉得可以请给颗星星):https://github.com/saucxs/saucxs.github.io.git 注意1:怎么避免 .md 文件被解析? Hexo原理就是hexo在执行hexo generate时会在本地先把博客生成的一套静态站点放到public文件夹中,在执行hexo depl

一步步搭建自己的博客 .NET版(3、注册登录功能)

前言 这次开发的博客主要功能或特点:    第一:可以兼容各终端,特别是手机端.    第二:到时会用到大量html5,炫啊.    第三:导入博客园的精华文章,并做分类.(不要封我)    第四:做个插件,任何网站上的技术文章都可以转发收藏 到本博客. 所以打算写个系类:<一步步搭建自己的博客> 一.一步步搭建自己的博客  .NET版(1.页面布局.blog迁移.数据加载) 二.一步步搭建自己的博客  .NET版(2.评论功能) 三.一步步搭建自己的博客  .NET版(3.注册登录功能) 四

django+SQLite搭建轻量级个人博客(二)基本配置

一.Django的工作模式 在Django里,由于 C层由框架自行处理,而 Django 里更关注的是模型(Model).模板(Template)和视图(Views),所以Django 也被称为 MTV框架 .在MTV开发模式中: 1.models,数据模型:这是一个抽象层,用来构建和操作你的web应用中的数据,模型是你的数据的唯一的.权威的信息源.它包含你所储存数据的必要字段和行为.通常,每个模型对应数据库中唯一的一张表. (models.py 文件存在的意义......) 2.templat

docker三剑客之docker-compose和搭建wordpress的博客

一.简介 Compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快速编排. 通过之前的介绍,我们知道使用一个 Dockerfile 模板文件,可以让用户很方便的定义一个单独的应用容器.然而,在日常工作中,经常会碰到需要多个容器相互配合来完成某项任务的情况.例如要实现一个 Web 项目,除了 Web 服务容器本身,往往还需要再加上后端的数据库服务容器,甚至还包括负载均衡容器等. Compose 恰好满足了这样的需求.它允许用户通过一个单独的 docker-com

0成本搭建个人技术博客和个人网站

摘要: 首先送上我的个人博客先睹为快 鲁边的个人博客 说说搭建个人博客的初衷,前段时间发现自己在博客网站上的文章配图没了,感觉很不可思议,就萌生了这样的想法,但真正驱使我去行动起来的原因是,最近有一次我发表了一篇文章,结果还要审核,最后告诉我审核不通过,好吧,我换了一个博客发表,结果给我封号了,封号了,心情一时难以言表.于是愤而起身,决定亲自搭建一个博客. 下面我们看正文. 一.前言 如果时间算是成本的话,那我的标题可能起错了. 1.1.为什么要搭建博客 相比较CSDN博客园简书而言,个人博客是

Flask入门小项目 - 搭建极简博客(7)

目录: Flask入门小项目 - 搭建极简博客(1)介绍与项目结构 Flask入门小项目 - 搭建极简博客(2)添加主页 Flask入门小项目 - 搭建极简博客(3)添加登录.登出功能 Flask入门小项目 - 搭建极简博客(4)添加注册功能 Flask入门小项目 - 搭建极简博客(5)添加写文章功能 Flask入门小项目 - 搭建极简博客(6)添加删除文章功能 Flask入门小项目 - 搭建极简博客(7)部署到服务器,实现外网访问 完整程序点这 零.效果 域名的话要等它备案完才能访问... 一

学做酷炫有爱的免费网页,学习 Github Page 教你分分钟搭建自己的博客

Github Page 网页搭建教程,教你分分钟搭建自己的博客 更多漂亮的网页搭建教程教程,请看这里:http://www.duobei.com/course/8506331668 1.注册Github账号 2.新建一个仓库,也就是我们代码要存放的位置 为我们仓库起个名字 3.为我们的仓库自动生成一个网页 点击Gihub Pages模块里的Automatic page generator 设置我们网页的Body内容 点击发布,生成我们的网页 按照 username.github.io/repos