django入门到精通⑧消息管理器和mysql数据库的互动
1.message_test/settings.py配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'app.templatetags',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'muke_lession_test',
'USER':'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
总路由配置
message_test/urls.py
from django.contrib import admin
from django.urls import path,include
from app import urls as app_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(app_urls))
]
2.常量的配置
app/consts.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-31 8:28 PM'
from enum import Enum
class MessageType(Enum):
info = "info"
warning = "warning"
error = "error"
danger = "danger"
delete = "delete"
MessageType.info.label = '信息'
MessageType.warning.label = '警告'
MessageType.error.label = '错误'
MessageType.danger.label = '危险'
MessageType.info.color = 'green'
MessageType.warning.color = 'orange'
MessageType.error.color = 'gray'
MessageType.danger.color = 'red'
MessageType.delete.color = 'yellow'
SensitiveWord = ['天气', '坏人', '不开心']
3.自定义过滤器的使用
app/templatetags/custom.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-31 9:03 PM'
import jieba
from django import template
from app.consts import SensitiveWord
import time
register = template.Library()
@register.filter(name='deep_check_message')
def deep_check(value):
# 只屏蔽关键词,替换为 * 号
cut_message = jieba.lcut(value)
new_message = []
for m in cut_message:
if m in SensitiveWord:
new_message.append('*')
else:
new_message.append(m)
if new_message:
return ''.join(new_message)
return value
@register.filter
def sample_check(value):
# 自定义的关键词过滤器
cut_message = jieba.lcut(value)
print(cut_message)
print(SensitiveWord)
check = list(set(cut_message) & set(SensitiveWord))
if len(check) != 0:
return '该消息涉及违禁词汇,已被屏蔽'
return value
@register.filter
def add_message_year(value, year):
return '{} {}'.format(value, year)
@register.filter
def date_convert(value):
timearray = time.localtime(value)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timearray)
return otherStyleTime
4.app/models.py的定义
# coding:utf-8
from django.db import models
from .consts import MessageType
class Message(models.Model):
content = models.TextField()
message_type = models.CharField(max_length=10, db_index=True)
created_time = models.IntegerField(default=0)
def __str__(self):
return 'type:{}, content:{}'.format(self.message_type, self.content)
@property
def message_typ(self):
try:
return MessageType[self.message_type]
except:
return MessageType.info
5.路由定义
app/urls.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-29 8:27 PM'
from django.urls import path
from .views import LessionThree, LessionFourPageOne, LessionFourPageTwo, DeleteMessage, UpdateMessage
urlpatterns = [
path('three/<str:message_type>', LessionThree.as_view(), name="three"),
path('fourPageOne/<str:message_type>', LessionFourPageOne.as_view()),
path('delete/', DeleteMessage.as_view()),
path('update/', UpdateMessage.as_view()),
path('fourPageTwo', LessionFourPageTwo.as_view(), name='fourpagetwo')
]
6.模板文件
templates/three.html
{% load custom %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if error %}
<h3>error {{ error }}</h3>
{% else %}
<label style="color:{{ message_type.color }}">{{ message_type.label }}</label>
<span style="color:{{ message_type.color }}">{{ message|deep_check_message|add_message_year:2020 }}</span>
{% endif %}
</body>
</html>
templates/four_page_one.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ error }}
</body>
</html>
templates/four_page_two.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% load custom %}
<h1>this page tow</h1>
{% for message in messages %}
<li style="color:{{ message.message_typ.color }}">
{{ message.id }} {{ message.content }} 时间:{{ message.created_time|date_convert }}
<a href="http://127.0.0.1:8000/delete?id={{ message.id }}">删除</a>
</li>
{% endfor %}
</body>
</html>
视图app/views.py
# coding:utf-8
import time
from django.views.generic import View
# from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from .consts import MessageType
from .models import Message
class LessionThree(View):
TEMPLATE = 'three.html'
def get(self, request, message_type):
data = {}
try:
message_type_obj = MessageType[message_type]
except Exception as e:
data['error'] = '没有这个消息类型{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
if not message:
data['error'] = '消息不能为空'
return render(request, self.TEMPLATE, data)
data['message'] = message
data['message_type'] = message_type_obj
# return HttpResponse(message_type)
return render(request, self.TEMPLATE, data)
class LessionFourPageOne(View):
TEMPLATE = 'four_page_one.html'
def get(self, request, message_type):
data = {}
try:
message_type_obj = MessageType[message_type]
except Exception as e:
data['error'] = '没有这个消息类型{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
if not message:
data['error'] = '消息不可为空'
return render(request, self.TEMPLATE, data)
Message.objects.create(
content=message,
message_type = message_type_obj.value,
created_time=time.time()
)
return redirect(reverse('fourpagetwo'))
class LessionFourPageTwo(View):
TEMPLATE = 'four_page_two.html'
def get(self, request):
data = {}
search = request.GET.get('search', '')
if search:
messages = Message.objects.filter(content__contains=search)
else:
messages = Message.objects.all()
data['messages'] = messages
return render(request, self.TEMPLATE, data)
class DeleteMessage(View):
def get(self, request):
id = int(request.GET.get("id", 'no such id'))
Message.objects.filter(id=id).delete()
return redirect(reverse('fourpagetwo'))
class UpdateMessage(View):
TEMPLATE = 'four_page_one.html'
def get(self, request):
data = {}
try:
id = int(request.GET.get("id", 'no such id'))
except Exception as e:
data['error'] = '找不到这个消息{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
print("message={}".format(message))
if not message:
data['error'] = '消息不可为空'
return render(request, self.TEMPLATE, data)
Message.objects.filter(id=id).update(content = message)
return redirect(reverse('fourpagetwo'))