目录
一、HttpRequest 对象
1.1 属性和方法
HttpRequest.scheme判断是http还是https
HttpRequest.path返回地址
HttpRequest.method判断是什么类型 ---GET:获得数据POST:修改,创建
HttpRequest.content_typeMIME
MIME是描述消息内容类型的因特网标准。包含文本、图像、音频、视频以及其他应用程序专用的数据。
HttpRequest.GET
HttpRequest.POST
HttpRequest.COOKIES
HttpRequest.get_host()返回网站服务器地址
HttpRequest.get_port()返回服务器主机端口
HttpRequest.is_secure()
HttpRequest.is_ajax()判断是否ajax请求
HttpRequest.get_full_path()
HttpRequest.build_absolute_uri(location)
HttpRequest.user
1.2 HttpRequest.FILES提交文件:
<MultiValueDict: {‘f1’: [<InMemoryUploadedFile: test.doc (application/msword)>]}>
form表单如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="f1">
<button>上传</button></form>
</body>
</html>
1.3 通过HttpRequest下载文件:
def download_file(request):
f=open('static_date/test.doc','rb')
response = HttpResponse(f, content_type='application/msword') # 参考MIME参考手册选择格式
response['Content-Disposition'] = 'attachment; filename="ftest.doc"'
# 中文urlquote(文件名称)
return response
1.4 MIME参考手册:
二、CBV(Class based views)
CBV是在视图里使用类处理请求
优点:
- 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
- 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
在view.py中:
from django.http import HttpResponse
from django.views import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')
在url.py中
from django.urls import path
from myapp.views import MyView
urlpatterns = [
path('about/', MyView.as_view()),
]
# Django的url收到请求后,是需要把这个请求分配给一个可调用的函数的,而不是一个class。针对这个问题,class-based view
# 提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,
# dispatch()方法会根据request的method的不同调用相应的方法来处理request(如get() , post()等)。到这里,这些方法
# 和function-based view差不多了,要接收request,得到一个response返回。如果方法没有定义,会抛出HttpResponseNotAllowed异常。
类的属性可以通过两种方法设置:
1.
from django.http import HttpResponse
from django.views import View
class GreetingView(View):
greeting = "Good Day"
def get(self, request):
return HttpResponse(self.greeting)
子类中只需继承:
class MorningGreetingView(GreetingView):
greeting = "Morning to ya"
2.在url中指定类的属性:在url中设置类的属性Python
urlpatterns = [
path('about/', GreetingView.as_view(greeting="G'day")),
]