请求对象Request
Request是Django为我们封装,在视图函数的第一个参数上,请求由django框架生成
包含字段
属性
- path 请求的完整路径
- method 请求方法,一般用GET,POST
- POST 类似字典,包含了post的所有参数
- GET 类似字典,包含了get的所有参数
- FILES 类似字典,包含上传的文件
- session 类似字典,表示会话
- cookie 字典,包含了所有cookie
GET,POST是请求数据的封装,数据结构是类字典结构,通过字典存储数据,key是可以重复的
passwd = request.POST.get(‘passwd’)
大写的是request的请求方式,小写的是传入参数的方法
开发中用这种,以列表的形式返回,request.GET.getlist(‘hobby’)
def login(request):
print('请求地址',request.path)
print('请求方法',request.method)
# 获取到的就是输入地址上的最后一个值
print('请求参数',request.GET.get('hobby'))
# 获取指定key对应的所有值,值以列表的形式返回
print('请求多个参数',request.GET.getlist('hobby'))
return render(request, 'youapp/login.html')
请求多个参数,在输入路径下?hobby=ssss&hobby=ooo&hobby=ddd
def dologin(request):
# 设置默认值
passwd = 'llll'
passwd = request.POST.get('passwd')
return HttpResponse('你的密码是%s'%passwd)
##根据不同的操作获取不同的值
def handleuser(request):
if request.method == 'GET':
# 获取用户
userid = request.GET.get('userid')
return HttpResponse('找到了')
elif request.method =='POST':
userid = request.POST.get('userid')
sex = request.POST.get('sex')
# object.sex = sex
# object.save()
return HttpResponse('你的手术成功')
else:
return HttpResponse('你的手术失败')
属性
content 返回的内容
status_code 响应状态吗
content-type MIME类型
方法
init 初始化内容
write(xxx)直接写出文本
flush() 冲刷
response
def sleep(request):
response = HttpResponse()
# response.content = '今年天气不错'
response.write('今天')
# 只要有写,就一定要加flash
response.flush()
return response
jsonResponse
返回json数据的请求,通常用在异步请求
def usernameIsValid(request):
data = {'msg':'ok','result':'over','status':200}
response = JsonResponse(data)
return response