Django_ 学员管理后台系统开发 (三)

  |   0 评论   |   0 浏览

  优化,和抽象代码,减少耦合度

  修改 view.py

  1
  2from django.http import HttpResponseRedirect
  3
  4from django.shortcuts import render
  5
  6from django.urls import reverse
  7
  8from django.views import View
  9
 10from student_sys.form import StudentForm
 11
 12from .models import Student
 13
 14# Create your views here.
 15
 16class IndexView(View):
 17
 18template_name = 'index.html'
 19
 20@staticmethod
 21
 22def get_content():
 23
 24students = Student.get_all()
 25
 26context = {
 27
 28'students':students
 29
 30}
 31
 32return context
 33
 34def get(self, request):
 35
 36context = self.get_content()
 37
 38form = StudentForm
 39
 40context.update({
 41
 42'form':form
 43
 44})
 45
 46return render(request, self.template_name, context=context)
 47
 48def post(self, request):
 49
 50form = StudentForm(request.POST)
 51
 52if form.is_valid():
 53
 54form.save()
 55
 56return HttpResponseRedirect(reverse('index'))
 57
 58context = self.get_content()
 59
 60context.update({
 61
 62'form': form
 63
 64})
 65
 66return render(request, self.template_name, context=context)
 67
 68# def index(request):
 69
 70# students = Student.get_all()
 71
 72# if request.method == 'POST':
 73
 74# form = StudentForm(request.POST)
 75
 76# if form.is_valid():
 77
 78# # cleaned_data = form.cleaned_data
 79
 80# # student = Student()
 81
 82# # student.name = cleaned_data['name']
 83
 84# # student.sex = cleaned_data['sex']
 85
 86# # student.email = cleaned_data['email']
 87
 88# # student.profession = cleaned_data['profession']
 89
 90# # student.qq = cleaned_data['qq']
 91
 92# # student.phone = cleaned_data['phone']
 93
 94# # student.save()
 95
 96# form.save()
 97
 98# return HttpResponseRedirect(reverse('index'))
 99
100# else:
101
102# form = StudentForm()
103
104#
105
106# context = {
107
108# 'students': students,
109
110# 'form': form
111
112# }
113
114# return render(request, 'index.html', context=context)
115

  被注释掉的是之前的写,上面的代码是优化后

  抽象成类之后,可以更好的复用代码,更加直观了,就算以后需要修改,也不用所有的需求都改一个函数

  当然我们不一定要用 class-base view,这不是必要的。因为我们没有这么写,也跑的挺欢的,也没有问题,差别不大。但是,需要注意的是,为了以后的变更好过,还是要分离处理逻辑

  即将编写流水式代码过渡到编写结构化的类

  修改我们 view.py

 1
 2from django.conf.urls import url
 3
 4from django.contrib import admin
 5
 6from django.urls import path
 7
 8from student_sys.views import IndexView
 9
10urlpatterns = [
11
12url(r'^$', IndexView.as_view(), name='index'),
13
14path('admin/', admin.site.urls),
15
16]
17

  as_view()是对 get 和 post 方法的封装

  编写一个测试程序的 middleware,主要是为了了解学习怎么去写

  middleware.py

 1
 2import time
 3
 4from django.urls import reverse
 5
 6from .middlemixin import MiddlewareMixin
 7
 8class TimeItMiddleware(MiddlewareMixin):
 9
10def process_request(self, request):
11
12self.start_time = time.time()
13
14return
15
16def process_view(self, request, func, *args, **kwargs):
17
18if request.path != reverse('index'):
19
20return None
21
22start = time.time()
23
24response = func(request)
25
26costed = time.time() - start
27
28print('process view: {:.2f}s'.format(costed))
29
30return response
31
32def process_exception(self, request, exception):
33
34pass
35
36def process_template_response(self, request, response):
37
38return response
39
40def process_response(self, request, response):
41
42costed = time.time() - self.start_time
43
44print('process response cose: {:.2f}s'.format(costed))
45
46return response
47

  作用是测试加载视图和程序响应的速度

  我们如果需要在请求头里面加东西,都可以在 process_template_response 这边添加

  修改 urls

 1
 2from django.conf.urls import url
 3
 4from django.contrib import admin
 5
 6from django.urls import path
 7
 8from student_sys.views import IndexView
 9
10urlpatterns = [
11
12url(r'^$', IndexView.as_view(), name='index'),
13
14path('admin/', admin.site.urls),
15
16]
17

  效果如下

  image.png

  编写 TestCase

  1
  2from django.test import TestCase, Client
  3
  4# Create your tests here.
  5
  6from .models import Student
  7
  8class StudentTestCase(TestCase):
  9
 10def setUp(self):
 11
 12Student.objects.create(
 13
 14name='sunwie',
 15
 16sex=1,
 17
 18email='[email protected]',
 19
 20profession='ops',
 21
 22qq='33',
 23
 24phone='222'
 25
 26)
 27
 28Student.objects.create(
 29
 30name='sunwie',
 31
 32sex=1,
 33
 34email='[email protected]',
 35
 36profession='ops',
 37
 38qq='33',
 39
 40phone='222'
 41
 42)
 43
 44def test_create_and_sex_show(self):
 45
 46student = Student.objects.create(
 47
 48name='mufeng',
 49
 50sex=1,
 51
 52email='[email protected]',
 53
 54profession='ops',
 55
 56qq='33',
 57
 58phone='222'
 59
 60)
 61
 62print(student.get_sex_display())
 63
 64self.assertEqual(student.get_sex_display(),'boy','性别和展示不一致')
 65
 66def test_filter(self):
 67
 68Student.objects.create(
 69
 70name='mufeng',
 71
 72sex=1,
 73
 74email='[email protected]',
 75
 76profession='ops',
 77
 78qq='33',
 79
 80phone='222'
 81
 82)
 83
 84name = 'mufeng'
 85
 86students = Student.objects.filter(name=name)
 87
 88self.assertEqual(students.count(),1,'应该只存在名称为 {} 的记录'.format(name))
 89
 90# view部分测试
 91
 92def test_get_index(self):
 93
 94client = Client()
 95
 96response = client.get('/')
 97
 98self.assertEqual(response.status_code, 200, 'status code must be 200!')
 99
100def test_post_student(self):
101
102client = Client()
103
104data = dict(
105
106name='test_for_post',
107
108sex=1,
109
110email='[email protected]',
111
112profession='程序员',
113
114qq='33',
115
116phone='3222'
117
118)
119
120response = client.post('/', data)
121
122self.assertEqual(response.status_code, 302, 'status code must be 302!')
123
124response = client.get('/')
125
126self.assertTrue(
127
128b'test_for_post' in response.content,
129
130'response must contain `test_for_post`'
131
132)
133

  基本上我在 GitHub 上看到的项目,多多少少会包含一些测试

  简单的学员管理系统就做完了,当然一个正常生产的项目不可能这么简单

  有没有小伙伴,一起学习 python 的,有的话在下面留言

---------------------------------------------------------------
>> 博客地址:https://blog.mufengs.com
>> 邮箱地址:[email protected]
>> 微信帐号:Do8080
>> Github : https://github.com/mufengcoding
---------------------------------------------------------------