1. Request:
request.mothed 请求方式 如:POST,GET request.POST.get() 获取POST的请求信息 request.POST.getlist() 获取多个POST的请求信息 request.GET.get() 获取GET的请求参数 request.body 获取请求体的信息,bytes类型显示,get方式没有请求体,post方式有请求体 request.scheme 获取http/https request.get_host() 获取ip地址和端口 request.path_info 获取url路径信息,不包含域名信息 request.get_full_path() 获取除域名外的所有信息
request.FILES.get() 获取上传的文件
前端上传文件代码
<form action="" method="post" enctype="multipart/form-data"> 上传文件的话,一定要在form表单中定义enctype="multipart/form-data"
<input type="file" name="my_file">
<button type="submit">提交</button>
</form>
后台获取上传文件的代码
class Upload(View):
def get(self,request):
return render(request,'upload.html')
def post(self,request):
file_name = request.FILES.get('my_file') 获取文件对象
with open(file_name.name,'wb') as f1: file_name.name是FILES自带的方法,可以直接取到文件名
for i in file_name.chunks(100): chunks()也是FILES自带的方法,括号内可以指定每次上传的大小,字节格式
f1.write(i)
return HttpResponse('上传成功')
2. Response:
HttpResponse (字符串) render (request,'html文件名',模板渲染参数{}字典格式) redirect (跳转地址) JsonResponse (字典) Django自带json转换功能,如果传一个其他类型的数据则需要写成 JsonResponse(字典,safe=False),如果使用json模块的话
如下:
import json
from django.http import JsonResponse
def json_data(request):
data_dict = {'name':'alex','age':99}
return HttpResponse(json.dumps(data_dict)) # Content-Type: text/html; charset=utf-8
# 通过JsonResponse传json格式数据
return JsonResponse(data_dict) # Content-Type: application/json
# 通过HttpResponse传json的方式,并改变Content-Type
return HttpResponse(json.dumps(data_dict),content_type='application/json') # 直接指定Content类型,Content-Type: application/json
# 另外一种改变Content-Type方式
ret = HttpResponse(json.dumps(data_dict))
ret['Content-Type'] = 'application/json'
return ret # Content-Type: application/json
# 通过JsonResponse传除了字典格式的数据类型
li = [1,2,3,4,5]
# return JsonResponse(li) # 会报错
return JsonResponse(li,safe=False) # 正确写法
浙公网安备 33010602011771号