Python-Django 视图层

1 request对象

method:请求方式
GET:get请求的参数(post请求,也可以携带参数)
POST:post请求的参数(本质是从bdoy中取出来,放到里面了)
COOKIES--->后面讲
META:字典(放着好多东西,前端传过来的,一定能从其中拿出来)
body:post提交的数据
path:请求的路径,不带参数
request.get_full_path() 请求路径,带参数
session---后面讲
user---后面讲
FILES
encoding:编码格式

2 HttpResponse对象

-三件套
-JsonResponse:往前端返回json格式数据(没有它,我可以自己写)
-转列表格式:指定safe=False
-中文字符问题:json_dumps_params={'ensure_ascii':False}

3 JsonResponse

# JsonResponse
url(r'^json$', app01_views.JasonRes),
def JasonRes(request):
dic={'id':1,'name':'lll六六六','publish':'laonanhai','publish_date':'2019-01-9','author':'dj'}
# import json
# return HttpResponse(json.dumps(dic,ensure_ascii=False))
return JsonResponse(dic,safe=False,json_dumps_params={'ensure_ascii':False})

(开车内容) wsgiref,uwsgi,---都遵循wsgi协议

-遵循一个协议wsgi(Web Server Gateway Interface web服务网关接口)

4 CBV(基于类的视图)和FBV(基于函数的视图)

-cbv:一个路由写一个类
-先定义一个类:继承自View
from django.views import View
class MyClass(View):
# 当前端发get请求,会响应到这个函数
def get(self, request):
return render(request,'index.html')
# 当前端发post请求,会响应到这个函数
def post(self,request):
print(request.POST.get('name'))
return HttpResponse('cbv--post')
-在路由层:
re_path('^myclass/$',views.MyClass.as_view()),

# CBV
url(r'^myclass/$', app01_views.Myclass.as_view()),
from django.views import View
class Myclass(View):
def get(self,request):
return render(request,'index.html')

def post(self,request):
print(request.POST.get('name'),request.POST.get('pwd'))
return HttpResponse('CBV--POST')

5 文件上传

-form表单默认提交的编码方式是enctype="application/x-www-form-urlencoded"
-前端:如果要form表单上传文件,必须指定编码方式为:multipart/form-data
-后端:
file=request.FILES.get('myfile')
with open(file.name,'wb') as f:
for line in file:
f.write(line)

# FILES
url(r'^file', app01_views.file_upload),
def file_upload(request):
if request.method=='GET':
return render(request,'file_upload.html')
else:
print(request.POST)
print(request.FILES)
from django.core.files.uploadedfile import InMemoryUploadedFile
file1=request.FILES.get('myfile1')
print(type(file1))
file2=request.FILES.get('myfile2')
import os,time
name=str(time.strftime("%Y-%m-%d"))+file1.name
print(name)
path=os.path.join('media',name)
print(path)
with open(path,'wb') as f:
for line in file1:
f.write(line)
# with open(file2.name,'wb') as f:
# for line in file2:
# f.write(line)
return HttpResponse('上传成功!')

<body>
<form action="" method="post" enctype="multipart/form-data">
{#<form action="" method="post" enctype="application/x-www-form-urlencoded">#}
<p>用户名 <input type="text" name="name"></p>
<input type="file" name="myfile1">
{# <input type="file" name="myfile2">#}
<input type="submit" name="submit">
</form>
</body>


6 前端提交数据编码格式:

-multipart/form-data(上传文件)
-application/x-www-form-urlencoded(默认编码)

7 图书管理系统表分析:

图书管理系统
-表:
book表
author表
publish表

-一对一:一对多的关系一旦确立,关联字段写在哪都可以
-一对多:一对多的关系一旦确立,关联关系写在多的一方
-多对多:多对多的关系,必须创建第三张表(中间表)

猜你喜欢

转载自www.cnblogs.com/du-jun/p/10246276.html
今日推荐