优化,和抽象代码,减少耦合度
修改 view.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from student_sys.form import StudentForm
from .models import Student
# Create your views here.
class IndexView(View):
template_name = 'index.html'
@staticmethod
def get_content():
students = Student.get_all()
context = {
'students':students
}
return context
def get(self, request):
context = self.get_content()
form = StudentForm
context.update({
'form':form
})
return render(request, self.template_name, context=context)
def post(self, request):
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('index'))
context = self.get_content()
context.update({
'form': form
})
return render(request, self.template_name, context=context)
# def index(request):
# students = Student.get_all()
# if request.method == 'POST':
# form = StudentForm(request.POST)
# if form.is_valid():
# # cleaned_data = form.cleaned_data
# # student = Student()
# # student.name = cleaned_data['name']
# # student.sex = cleaned_data['sex']
# # student.email = cleaned_data['email']
# # student.profession = cleaned_data['profession']
# # student.qq = cleaned_data['qq']
# # student.phone = cleaned_data['phone']
# # student.save()
# form.save()
# return HttpResponseRedirect(reverse('index'))
# else:
# form = StudentForm()
#
# context = {
# 'students': students,
# 'form': form
# }
# return render(request, 'index.html', context=context)
被注释掉的是之前的写,上面的代码是优化后
抽象成类之后,可以更好的复用代码,更加直观了,就算以后需要修改,也不用所有的需求都改一个函数
当然我们不一定要用 class-base view,这不是必要的。因为我们没有这么写,也跑的挺欢的,也没有问题,差别不大。但是,需要注意的是,为了以后的变更好过,还是要分离处理逻辑
即将编写流水式代码过渡到编写结构化的类
修改我们 view.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from student_sys.views import IndexView
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
path('admin/', admin.site.urls),
]
as_view()是对 get 和 post 方法的封装
编写一个测试程序的 middleware,主要是为了了解学习怎么去写
middleware.py
import time
from django.urls import reverse
from .middlemixin import MiddlewareMixin
class TimeItMiddleware(MiddlewareMixin):
def process_request(self, request):
self.start_time = time.time()
return
def process_view(self, request, func, *args, **kwargs):
if request.path != reverse('index'):
return None
start = time.time()
response = func(request)
costed = time.time() - start
print('process view: {:.2f}s'.format(costed))
return response
def process_exception(self, request, exception):
pass
def process_template_response(self, request, response):
return response
def process_response(self, request, response):
costed = time.time() - self.start_time
print('process response cose: {:.2f}s'.format(costed))
return response
作用是测试加载视图和程序响应的速度
我们如果需要在请求头里面加东西,都可以在 process_template_response 这边添加
修改 urls
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from student_sys.views import IndexView
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
path('admin/', admin.site.urls),
]
效果如下
编写 TestCase
from django.test import TestCase, Client
# Create your tests here.
from .models import Student
class StudentTestCase(TestCase):
def setUp(self):
Student.objects.create(
name='sunwie',
sex=1,
email='dd@qq.com',
profession='ops',
qq='33',
phone='222'
)
Student.objects.create(
name='sunwie',
sex=1,
email='dd@qq.com',
profession='ops',
qq='33',
phone='222'
)
def test_create_and_sex_show(self):
student = Student.objects.create(
name='mufeng',
sex=1,
email='dd@qq.com',
profession='ops',
qq='33',
phone='222'
)
print(student.get_sex_display())
self.assertEqual(student.get_sex_display(),'boy','性别和展示不一致')
def test_filter(self):
Student.objects.create(
name='mufeng',
sex=1,
email='dd@qq.com',
profession='ops',
qq='33',
phone='222'
)
name = 'mufeng'
students = Student.objects.filter(name=name)
self.assertEqual(students.count(),1,'应该只存在名称为 {} 的记录'.format(name))
# view部分测试
def test_get_index(self):
client = Client()
response = client.get('/')
self.assertEqual(response.status_code, 200, 'status code must be 200!')
def test_post_student(self):
client = Client()
data = dict(
name='test_for_post',
sex=1,
email='2@qq.com',
profession='程序员',
qq='33',
phone='3222'
)
response = client.post('/', data)
self.assertEqual(response.status_code, 302, 'status code must be 302!')
response = client.get('/')
self.assertTrue(
b'test_for_post' in response.content,
'response must contain `test_for_post`'
)
基本上我在 github 上看到的项目,多多少少会包含一些测试
简单的学员管理系统就做完了,当然一个正常生产的项目不可能这么简单
有没有小伙伴,一起学习 python 的,有的话在下面留言
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于