view

一  CBV, FBV
cbv: 基于类的视图,业务逻辑 直接用函数处理逻辑业务( class based view)
fbv: 基于函数的视图,业务逻辑 用类的概念处理逻辑业务(function based view)

二.
from django.views import View

class AddPublisher(View):
def get(self, request):
pass
def post(self, request):
pass

tip: 继承views文件中的View,
重写pot, post方法, 修改自己需要处理的业务逻辑
使用入口:
url(r'add_publisher' , views.AddPublisher.as_view())
这个函数在Django程序开启后立即执行,as_view的方法,
返回一个view函数, 这个函数携带着一些属性和方法,(暂时不做细究)
函数在请求进来之后执行,并且实例化,匹配url请求方式, 依照请求方式
执行对应的方法,这里利用了反射,将请求方式GET, POST, PUT..8个方法放置在一个列表中,如果请求方式不在列表中,也会返回一个方法给handler并且执行


三 .给CBV加装饰器:
导入模块
import time
from django.utils.decorators import method_decorator
def timer(func)
def inner(*arge, **kwargs)
print(time.tieme()
ret = func()
print(time.time())
return ret
return inner
1, 加载装饰器到get/post的方法上面: # 放置在不同的请求方式上面,
@method_decorator(timer)
def post(self, request)

2. 加载到self.dispatch方法上面: (所有请求的执行完毕都生效)
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs): # 这个方法是匹配请求方式的: GET or POST or...
...

3. 加载到类上面 : 注意这里不会有顺序问题,装饰器只会给name对应的方法加装饰器,不重叠,不是多层嵌套
@method_decorator(timer, name='post')
@method_decorator(timer, name='get')
class AddPublisher(View):



tip: 区别 : 传参数会有区别, 一个类方法携带了self, 函数不携带self ,传request的时候注意下
1. 不使用method_decorator

func: <function AddPublisher.dispatch at 0x00000163735176A8>
args :<app01.views.AddPublisher object at 0x00000163735F7EF0> <WSGIRequest: GET '/add_publisher/'>

2. 使用method_decorator

func:<function method_decorator.<locals>._dec.<locals>._wrapper.<locals>.bound_func at 0x0000019664B4A378>
arsgs: <WSGIRequest: GET '/add_publisher/'>


四。 HttpResponse中 request对象:请求进来后生成的对象 : 这个对象包含请求中所有的信息
属性:request.path_info: 用户访问的 url, 不包括域名参数等
request.get_host(): 主机信息
request.get_full_path(): 路径信息 + 参数
request.GET : 对象{} [] get()
request.POST : 对象{} [] get()

request.FILES: 发送上传文件的请求
上传文件注意事项: 1. form表单的enctype='multipart/form-data'
2. request.FILES中获取文件对象 (文件缓存着)
3. 使用文件对象的chunks()


HttpResponse 子类JsonResponse
from django.http import JsonResponse
JsonResponse: 生成JSON编码的响应
response = JsonResponse({'foo': 'bar'})
print(response.content)
b'{"foo": "bar"}'

JsonResponse([1,2,3], safe=false) : 设置参数, 。
from django.http import JsonResponse

def json_test(request):
data = {'name': 'alex', 'pwd': 'alexdsb'}

return JsonResponse(data) # Content-Type: application/json
# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8 # 设置请求头文本类型
posted @ 2018-12-04 22:17  python传言  阅读(1120)  评论(0编辑  收藏  举报