内容回顾
1. 开发模式
普通开发方式(前后端放在一起写)
前后端分离
2. 后端开发
为前端提供URL(API/接口的开发)
注:永远返回HttpResponse
3. Django FBV、CBV
FBV,function base view
from django.shortcuts import HttpResponse import json def users(request): user_list = [‘lcg‘,‘superman‘] return HttpResponse(json.dumps((user_list)))
CBV,class base view
路由:
url(r‘^students/‘, views.StudentsView.as_view()),
视图:
from django.shortcuts import HttpResponse from django.views import View class StudentsView(View): def get(self,request,*args,**kwargs): return HttpResponse(‘GET‘) def post(self, request, *args, **kwargs): return HttpResponse(‘POST‘) def put(self, request, *args, **kwargs): return HttpResponse(‘PUT‘) def delete(self, request, *args, **kwargs): return HttpResponse(‘DELETE‘)
4. 列表生成时
class Foo: pass class Bar: pass v = [item() for item in [Foo,Bar]]
结果v是一个对象列表
v = [] for i in [Foo,Bar]: obj = i() v.append(obj)
5. 面向对象
封装
5.1 对同一类方法封装到类中
class File: 文件增删改查方法 Class DB: 数据库的方法
5.2 将数据封装到对象中
class File: def __init__(self,a1,a2): self.a1 = a1 self.xxx = a2 def get:... def delete:... def update:... def add:... obj1 = File(123,666) obj2 = File(456,999)
PS: 扩展
class Request(object): def __init__(self,obj): self.obj = obj @property def user(self): return self.obj.authticate() class Auth(object): def __init__(self,name,age): self.name = name self.age = age def authticate(self): return self.name class APIView(object): def dispatch(self): self.f2() def f2(self): a = Auth(‘lcg‘,18) b = Auth(‘小明‘,18) req = Request(b) print(req.user) obj = APIView() obj.dispatch()
# 输出结果:小明
---待续---