视图层 views.py
FBV与CBV
FBV:
def index(request):
return HttpResponse('index')
CBV
url(r'^login/',views.MyLogin.as_view())
from django.views import View
class MyLogin(View):
def get(self,request):
return render(request,'form.html')
def post(self,request):
return HttpResponse('post方法')
CBV添加装饰器
from django.views import View
from django.utils.decorators import method_decorator
CBV中django不建议你直接给类的方法加装饰器
# @method_decorator(login_auth,name='get')
# @method_decorator(login_auth,name='post')
class MyLogin(View):
@method_decorator(login_auth) # 方式3:类的所有方法都装饰
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# @method_decorator(login_auth)
def get(self,request):
return HttpResponse("get请求")
def post(self,request):
return HttpResponse('post请求')
请求:
request对象方法
request.method
request.POST
request.POST.get() # 只获取列表最后一个元素
request.POST.getlist() # 直接将列表取出 不支持负数索引
request.GET
request.GET.get() # 只获取列表最后一个元素
request.GET.getlist() # 直接将列表取出 不支持负数索引
get请求 携带的数据 大小限制 大概4KB
post请求 没有大小限制
request.FILES
request.body # 原生的浏览器发过来的二进制数据
request.path
request.path_info
request.get_full_path() 能过获取完整的url及问号后面的参数
print(request.path) # /app01/ab_file/
print(request.path_info) # /app01/ab_file/
print(request.get_full_path()) # /app01/ab_file/?username=jason
响应:
三板斧
视图函数必须要返回一个HttpResponse对象
render简单内部原理
from django.template import Template,Context
res = Template('<h1>{{ user }}</h1>')
con = Context({'user':{'username':'jason','password':123}})
ret = res.render(con)
print(ret)
return HttpResponse(ret)
HttpResponse
return HttpResponse('ok')
render
return render(request,'home.html',locals())
redirect
重定向
return redirect('https://www.mzitu.com/')
return redirect('/home/')
JsonResponse对象
import json
from django.http import JsonResponse
def ab_json(request):
# 先转成json格式字符串,然后返回
json_str = json.dumps(user_dict,ensure_ascii=False)
return HttpResponse(json_str)
return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
return JsonResponse(l,safe=False)
# 默认只能序列化字典 序列化其他需要加safe参数