第四章 FBV视图
FBV(function base views):在视图里定义函数
4.1设置响应方式
4.1.1返回响应内容
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
value='a test'
print(value)
return render(request,'index.html')
def myvariable(request,year,month,day):
return HttpResponse(str(year)+'/'+str(month)+'/'+str('day'))
HttpResponse的参数:第一个是响应内容,一般是网页内容或者json数据,第二个参数是HTTP状态码
render的语法:
render(request,template_name,context=None,content_type=None,status=None,using=None)
request:浏览器向服务器发送的请求对象
template_name:模板文件名
context:对模板变量赋值,一般是字典形式
content_type:响应内容的数据格式
status:状态码
using:设置模板引擎
当视图函数中有多个变量时,使用以下render语法:
return render(request,template_name,locals())#只需更改模板文件名
4.1.2设置重定向
HttpResponseRedirect,HttpResponsePermanentRedirect只能传入路由地址
redirect 函数:支持路由地址或路由命名,基于以上两个类做出的改进。
return redirect("index:shop",permanent=True)
url=reverse('index:shop')
#设置302重定向(临时)
return HttpResponseRedirect(url)
#设置301重定向(永久)
return HttpResponsePermanentRedirect(url)
4.1.3异常响应
设置全局404和500的异常响应,只需要在项目的urls.py中设置变量handler404和handler500.
变量值是指向某个项目应用的视图函数,视图函数需要设置相应的模板文件和响应状态码。
项目文件夹下的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)
4.1.4文件下载
三种方式实现下载
HttpResponse:占用内存
StreamingHttpResponse(流式响应输出,分段处理大规模数据响应和文件传输响应)
FileResponse(流式响应输出,分段处理文件传输响应)
#HttpResponse
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')
#StreamingHttpResponse
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')
#FileResponse
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')
4.2HTTP请求对象
4.2.1 HTTP请求
有8种,常用get和put
(1) GET请求的请求参数是在路由地址后加?与参数内容,参数内容以key=value形式表示,如果有多个参数,用&隔开
(2) POST请求参数一般以表单形式传递,通常使用form表单,并且form标签的method属性设为POST.
(3) django收到HTTP请求后,根据请求携带的参数与信息创建一个WSGIRequest对象,作为视图函数的首个参数request.
WSGIRequest类属性:
COOKIE:获取客户端的cookie信息
FILES:django.http.request.QueryDict对象
GET:获取GET请求的请求参数,QueryDict对象
POST:获取POST请求的请求参数,QueryDict对象
META:获取客户端请求头信息
method:获取当前请求的请求方式
path:获取当前请求的路由地址
session:存放用户信息
user:当前用户
(4)由于WSGIRequest继承并重写HttpRequest类,所以HttpRequest定义的方法同样适用于类WSGIRequest
is_secure():是否采用https协议
is_ajax():是否采用ajax发生HTTP请求
get_host():获取服务器的域名
get_full_path():返回路由地址
get_raw_uri():获取完整的网址信息
4.2.2文件上传功能
4.2.3反爬虫机制
未完。。。。
参考书籍《Django web应用开发实战》