django1与2路由的差别

在django1中的url在django2中为re_path
django2中新增了path
1.from django.urls import path
2.不支持正则,精准匹配
3.有5个转换器(int,str,slug,path,uuid)
4.自定义转换器:
1 写一个类:
class Test:
regex = '[0-9]{4}'
def to_python(self, value):
# 写一堆处理
value=value+'aaa'
return value
def to_url(self, value):
return '%04d' % value
2 from django.urls import register_converter
3 register_converter(Test,'ttt')
4 path('index/<ttt:year>', views.index,name='index'),

MVC和MTV

    M          T                 V

	models	   template         views

	M          V                 C(路由+views)
models 模板 控制器 其实MVC与MTV是一样的,django中为MTV,数据交互层,视图层以及控制层

视图层:request对象

request对象:
# form表单,不写method ,默认是get请求
# 1 什么情况下用get:请求数据,请求页面,
# 2 用post请求:向服务器提交数据
# request.GET 字典
# request.POST 字典
# 请求的类型
# print(request.method)
# 路径
# http://127.0.0.1:8000/index/ppp/dddd/?name=lqz
# 协议:ip地址和端口/路径?参数(数据)
# print(request.path) -->/index/ppp/dddd/
# print(request.get_full_path()) -->/index/ppp/dddd/?name=lqz

三件套

render
HttpResponse
redirect

JsonResponse

向前端页面发json格式字符串
封装了json
from django.http import JsonResponse dic={'name':'lqz','age':18}
li=[1,2,3,4] return JsonResponse(li,safe=False)

CBV和FBV

CBV(class base view)和FBV(function base view)

cbv:

from django.views import View
class Test(View):
def dispatch(self, request, *args, **kwargs): # 分发
# 可加逻辑判断语句
obj=super().dispatch(request, *args, **kwargs)
# 可加逻辑判断语句
return obj
def get(self,request):
obj= render(request,'index.html')
print(type(obj))
return obj
def post(self,request):
return HttpResponse('ok') urls中:
re_path(r'index/', views.Test.as_view()),

简单文件上传

html中:
<form action="" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="name">
密码:<input type="text" name="password">
文件:<input type="file" name="myfile">
<input type="submit">
</form> views中
class Cbv(View):
def dispatch(self, request, *args, **kwargs):
obj = super().dispatch(request, *args, **kwargs)
return obj def get(self,request):
return render(request,'index.html') def post(self,request):
aaa = request.FILES.get('myfile')
with open(aaa.name,'wb') as f:
for line in aaa.chunks():
f.write(line)
return HttpResponse('ok')
05-11 17:54