您的位置:首页 > 产品设计 > UI/UE

8. Django学习笔记——视图及HttpRequest 和HttpResponse

2019-04-01 23:56 1041 查看

文章目录


Django中的视图主要用来接受Web请求,并做出响应。
视图的响应分为两大类:
 1)以Json数据形式返回:
JsonResponse({'name':'张三','age':33})

 2)以网页的形式返回:
  2.1)重定向到另一个网页
HttpResponseRedirect('http://www.baidu.com')

  2.2)错误视图(40X,50X)
(HttpResponseNotFound,HttpResponseForbidden,HttpResponseNotAllowed等)

视图参数:
 1)一个HttpRequest的实例,一般命名为request;
 2)通过url正则表达式传递过来的参数;
 位置:通常在应用下的views.py中定义。
错误视图:
 1) 404视图 (页面没找到)
 2) 400视图 (客户操作错误)
 3) 500视图 (服务器内部错误)
自定义错误视图
 1.在工程的templates文件夹下创建对应的 错误文件.html;
 2.在文件中定义自己的错误样式。
3.settings.py 中设置:

Debug=False
ALLOWED_HOSTS=[*]
TEMPLATES中 'DIRS': [os.path.join(BASE_DIR,'templates')]

response响应

# return HttpResponse('hello response')
# return render(request, 'httpApp/index.html')
# return JsonResponse({'name':'张三', 'age':33})
# return HttpResponseRedirect('http://www.baidu.com')  # 重定向
# return HttpResponseNotFound('Not Found')  # 错误视图

1,HttpRequest

服务器在接收到Http请求后,会根据报文创建HttpRequest对象;
视图中的第一个参数就是HttpRequest对象;
Django框架接收到http请求之后会将http请求包装为HttpRequest对象,之后传递给视图。
HttpRequest和HttpResponse属性和方法的详细说明
常用属性和方法:
属性:

path		请求的完整路径
method		请求的方法,常用GET,POST
encoding	编码方式,常用utf-8
GET		 	类似字典的参数,包含了get的所有参数
POST	 	类似字典的参数,包含了post所有参数
FILES	 	类似字典的参数,包含了上传的文件
COOKIES	字典,包含了所有COOKIE
session 		类似字典,表示会话

方法:

is_ajax()	 判断是否是ajax(),通常用在移动端和JS中
get_full_path()	返回包含参数字符串的请求路径 ./httpapp/index/?name=zhang&name=li&age=22

request请求例子:
网站:http://127.0.0.1:8001/httpapp/index/?name=11&age=22&name=33
对应信息:

print(request.path)   # /httpapp/index/, 路径
print(request.method)   # GET , 请求方式
print(request.encoding)  # None, 编码类型
print(request.GET)  # <QueryDict:{'name': ['11', '33'],'age': ['22']}> , GET请求提交的参数
print(request.POST)  # <QueryDict: {}> , POST请求提交过来的参数
print(request.FILES)  # <MultiValueDict: {}> , 文件上传的内容

print(request.COOKIES)  # {'csrftoken': 'b7Fm6ysbmnWKJX8pplQd3211ewa6eSxJ9TZgGzH7vEdrYO05PIUJSzCGxivf7E2D'}
print(request.session)  # <django.contrib.sessions.backends.db.SessionStore object at 0x7f70fe8a1c50>

print(request.is_ajax())  # False, 是否使用ajax请求
print(request.get_full_path())  # /httpapp/index/?name=11&age=22&name=33
print(request.GET.get('name'))  # 33
print(request.GET.getlist('name'))  # ['11', '33']

2,HttpResponse

服务器返回给客户端的数据。
HttpResponse由程序猿自己创建:
 1)不使用模板,直接调用HttpResponse(),返回HttpResponse对象。
 2)调用模板,进行渲染。
  2.1) 先load模板,再渲染
  2.2) 直接使用render一步到位

render(request,template_name[,context])
request 		请求体对象
template_name	模板路径
context		字典参数,用来填坑

属性:

content		   返回的内容
charset		编码格式
status_code	响应状态码(200,3xx,404,5xx)

方法:

init				初始化内容
write(xxx)			直接写出文本
flush()				冲刷缓冲区
set_cookie(key,value='xxx',max_age=None)  设置cookie
delete_cookie(key)	 删除cookie

HttpResponse子类
 1)HttpResponseRedirect:响应重定向:可以实现服务器内部跳转
  

return HttpResponseRedict('/grade/2017')

  使用的时候推荐使用反向解析。
 2)JsonResponse:返回Json数据的请求,通常用在异步请求上
 3)JsonResponse(dict):返回json数据时,Content-type是application/json

示例:# response响应的属性

response = HttpResponse('hello response')
response.content = 'hello 宝强'  # 设置内容
response.write(' hello 马蓉')  # 追加内容
response.status_code = 404
return response

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: