视图基础知识1
1.FBV视图设置响应方式
1.1返回相应内容
使用视图函数处理HTTP请求,即在视图里定义def函数,这种方式为FBV。
网站的运行原理是遵从HTTP协议,分为HTTP请求和HTTP响应。HTTP响应方式也称为HTTP状态码,分为五种状态:消息、成功、重定向、请求错误和服务器错误。如果以使用频率划分,则HTTP状态码可分为:成功、重定向和异常响应(请求错误和服务器错误)。
HttpResponse(‘hello world’) 状态码200,请求已成功被服务器接收
HttpResponseRedirect(’/’) 状态码302,重定向首页地址
HttpResponsePernanentRedirect(’/’)状态码301,永久定向首页地址
HttpResponseBadRequest(‘400’) 状态码400,访问的页面不存在或请求错误
HttpResponseNotFound(‘404’) 状态码404,网页不存在或网页的URL失效
HttpResponseForbidden(403’) 状态码403,没有访问权限
HttpResponseNotAllowed(‘405’) 状态码405,不允许使用该请求方式
HttpResponseServerError(‘500’)状态码500,服务器内容错误
JsonResponse({‘foo’:‘bar’}) 默认状态码200,响应内容为JSON数据
StreamingHttpResponse() 默认状态码200,响应内容以流式输出
render(request,template_name,context=None,content_type=None,status=None,using=None)
render函数的使用方法,参数request,template_name是必需参数,其余为可选参数,说明如下:
- request 浏览器向服务器发送请求对象
- template_name 设置模板文件名,用于生成网页内容
- context 对模板上下文(模板变量)赋值,以字典格式表示,默认为空字典
- content_type 响应内容的数据格式,一般情况下默认
- status HTTP状态码,默认200
- using 模板引擎设置
context中的字典变量用法
value = {'title': 'Wow,Django'}
.....
return render(request, 'index.html', context = value)
....
在模板中
{{title}}
在实际开发中,如果视图传递变量过多,context会非常冗余,因此这个位置可以使用locals()来取代参数context。
return render(request, 'index.html', locals())
1.2.设置重定向
Django重定向类:HttpResponseRedirect、HttpResponsePermanentRedirect
重定向函数:redirect.
重定向的状态码为301和302,301为永久跳转,302为临时跳转,两者区别在于搜索引擎的页面抓取,301重定向为永久性,搜索引擎会用新的网址替换之前旧的网址;302为临时定向,搜索引擎会保留旧的网址。
redirect函数使用方式:
redirect(to, *args, permanent=False, **kwargs)
- 判断参数permanent的真假性来选择重定向的函数。若参数permanent为True,则调用HttpResponsePermanentRedirect来完成重定向过程,若为False,则调用HttpResponseRedirect。
- 由于两个重定向类支持路由地址的转入,因此函数redirect调用reslve_url方法对to进行判断,若参数to是路由地址,则直接将参数to的参数值返回;若参数to是路由名,则使用reverse函数转换为路由地址;若参数to是模型对象,则将模型对象转换成对应的路由地址。
1.3.异常响应
异常响应通常是指404或500,使用render函数,将状态值status设置为404或500即可。
见代码示例即可(代码示例来自《Django Web应用开发实战》)
项目的urls.py
from django.urls import path, include
urlpatterns = [
# 指向index的路由文件urls.py
path('', include(('index.urls', 'index'), namespace='index')),
]
# 全局404页面配置
handler404 = 'index.views.pag_not_found'
# 全局500页面配置
handler500 = 'index.views.page_error'
app的views.py文件
from django.shortcuts import render
from django.http import Http404
def index(request):
if request.GET.get('error', ''):
raise Http404("page does not exist")
else:
return render(request, 'index.html')
def pag_not_found(request):
"""全局404的配置函数 """
return render(request, '404.html', status=404)
def page_error(request):
"""全局500的配置函数 """
return render(request, '500.html', status=500)
如果需要验证该响应,需要在settings.py中将DEBUG设置为False。
1.4.文件下载
三种文件下载功能
HttpResponse是所有响应的核心
StreamingHttpResponse 流式响应输出,用于大规模数据响应和文件传输响应
FileResponse 只用于文件传输响应
App中urls.py代码如下:
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.http import StreamingHttpResponse
from django.http import FileResponse
def index(request):
return render(request, 'index.html')
def download1(request):
file_path = 'D:\cat.jpg'
try:
r = HttpResponse(open(file_path, 'rb'))
r['content_type'] = 'application/octet-stream'
r['Content-Disposition'] = 'attachment; filename=cat.jpg'
return r
except Exception:
raise Http404('Download error')
def download2(request):
file_path = 'D:\duck.jpg'
try:
r = StreamingHttpResponse(open(file_path, 'rb'))
r['content_type'] = 'application/octet-stream'
r['Content-Disposition'] = 'attachment; filename=duck.jpg'
return r
except Exception:
raise Http404('Download error')
def download3(request):
file_path = 'D:\dog.jpg'
try:
f = open(file_path, 'rb')
r = FileResponse(f, as_attachment=True, filename='dog.jpg')
return r
except Exception:
raise Http404('Download error')
HttpResponse会占用内存,因而在传输较大文件时会占用很多内存,因而推荐使用 StreamingHttpResponse与FileResponse。
StreamingHttpResponse支持数据和文件输出,因此在使用时需要设置响应输出类型和方式,而FileResponse只需要设置3个参数即可完成文件下载功能。