1.Django的View(视图)
1.1CBV和FBV
- FBV function based view 基于函数视图
CBV class based view 基于类视图
FBV版
# FBV版添加班级 def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
- CBV版
#新增出版社更改成一个类 from django.views import View class AddClass(View): """处理get请求""" def get(self, request): return render(request, "add_class.html") def post(self, request): """处理post请求""" class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/")
- 在起CBV时,urls.py中也做对应的修改
url(r"^add_class/$",view.AddClass.as_view())
as_view()的流程
1.项目启动加载url.py时 执行 AddClass.as_view()------->view函数(AddClass是个类)
2.请求到来的时候执行view函数
- 实例化类----> self = cls(**initkwargs)
- 执行self.dispatch(request, *args, **kwargs)
- 判断请求方式是否被允许
- 允许 通过反射获取到对应请求方式的方法 ——》 handler
- 不允许 self.http_method_not_allowed ——》handler
- 执行handler(request,*args,**kwargs)
- 返回响应 —— 》 浏览器
源码解析:
1.2使用装饰器装饰FBV
- FBV本身就是一个函数,所以和给普通的函数加装饰器无差:
#装饰器用来装饰add_class def wrapper(func): def inner(*args, **kwargs): start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() print("used:", end_time-start_time) return ret return inner # FBV版添加班级 @wrapper def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
1.3使用装饰器装饰CBV
类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。
Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。
示例:
from django.views import View from django.utils.decorators import method_decorator class AddClass(View): @method_decorator(wrapper) def get(self, request): return render(request, "add_class.html") def post(self, request): class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") #注意装饰器要写在被装饰方法或函数上面
#也可以加在类上 @method_decorator(wrapper,name="post") @method_decorator(wrapper,name="post") class AddPublisher(View):
不使用method_decorator装饰类与使用的区别?
def wrapper(func): def inner(*args): pass return inner #不使用method_decorator func <function AddPublisher.get at 0x000001FC8C358598> args (<app01.views.AddPublisher object at 0x000001FC8C432C50>, <WSGIRequest: GET '/add_publisher/'>) #使用method_decorator之后 func <function method_decorator.<locals>._dec.<locals>._wrapper.<locals>.bound_func at 0x0000015185F7C0D0> args (<WSGIRequest: GET '/add_publisher/'>,) #不使用method_decorator第二个参数才是request对象
CBV装饰器拓展
class Login(View): def dispatch(self, request, *args, **kwargs): print('before') obj = super(Login,self).dispatch(request, *args, **kwargs) print('after') return obj def get(self,request): return render(request,'login.html') def post(self,request): print(request.POST.get('user')) return HttpResponse('Login.post') # 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。
2.Request对象
- 当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpRequest对象。
Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。
1.请求相关常用值
方法 | 用途 |
---|---|
path_info | 返回用户访问url,不包括域名(不包括IP和端口 不包含参数) |
method | 请求中使用的HTTP方法的字符串表示,全大写表示。 |
GET | 包含所有HTTP GET参数的类字典对象 |
POST | 包含所有HTTP POST参数的类字典对象 |
body | 请求体,byte类型 request.POST的数据就是从body里面提取到的 |
def temp(request): print(request.path_info) return render(request,"temp.html") #/temp/ #body示例 class AddClass(View): def post(self,request): print(request.body) return redirect("/temp/") def get(self,request): return render(request,"add_class.html") #网页输入helloword #打印结果:b'csrfmiddlewaretoken=UvQwOKX3XdauRqH4vGquU2Si0JSagszTGFQgKqPzgOU6k6XJrYIVjfrjxkARv9kt&do=helloworld' #csrfmiddlewaretoken=UvQwOKX3XdauRqH4vGquU2Si0JSagszTGFQgKqPzgOU6k6XJrYIVjfrjxkARv9kt 为中间件 #do=helloworld form表单内容,输入汉字会自动转为urlcode
#文件上传练习: #form 表单 参数 enctype="multipart/form-data" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" enctype="multipart/form-data" method="post"> {% csrf_token %} 提交<input type="file" name="mtv" > <button>提交</button> </form> </body> </html> def upload(request): if request.method == "POST": gc = request.FILES print("gc",gc,type(gc)) file = request.FILES.get("mtv") print(file,type(file)) print(file.name,type(file.name)) with open("mtv.png",'wb') as f: for item in file.chunks(): f.write(item) return HttpResponse("<h1>成功</h1>") return render(request,"upload.html") #gc <MultiValueDict: {'mtv': [<InMemoryUploadedFile: 1.png (image/png)>]}> <class 'django.utils.datastructures.MultiValueDict'> #1.png <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> #1.png <class 'str'>
2.属性
django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性。
除了特殊说明的之外,其他均为只读的。
HttpRequest.scheme
- 表示请求方案的字符串(通常为http或https)
def temp(request): print(request.scheme) return render(request,"temp.html") #http
HttpRequest.body
- 一个字符串,代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用,例如:二进制图片、XML,Json等。但是,如果要处理表单数据的时候,推荐还是使用 HttpRequest.POST。另外,我们还可以用 python 的类文件方法去操作它,详情参考 HttpRequest.read()
HttpRequest.path
一个字符串,表示请求的路径组件(不含域名)。
def temp(request): print(request.path) return render(request,"temp.html") #/temp/
HttpRequest.method
一个字符串,表示请求使用的HTTP 方法。必须使用大写。
def temp(request): print(request.method) return render(request,"temp.html") #GET
HttpRequest.encoding
- 一个字符串,表示提交的数据的编码方式(如果为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。这个属性是可写的,你可以修改它来修改访问表单数据使用的编码。接下来对属性的任何访问(例如从 GET 或 POST 中读取数据)将使用新的 encoding 值。如果你知道表单数据的编码不是 DEFAULT_CHARSET ,则使用它。
def temp(request): print(request.encoding) return render(request,"temp.html") #None #如果为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8'
HttpRequest.GET
- 一个类似于字典的对象,包含 HTTP GET 的所有参数。详情请参考 QueryDict 对象。
- HttpRequest.POST
- 一个类似于字典的对象,如果请求中包含表单数据,则将这些数据封装成 QueryDict 对象。
- 注意:POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单,但是表单中没有任何的数据,QueryDict 对象依然会被创建。因此,不应该使用 if request.POST 来检查使用的是否是POST 方法;应该使用 if request.method == "POST"。另外:如果使用 POST 上传文件的话,文件信息将包含在 FILES 属性中。
HttpRequest.COOKIES
一个标准的Python 字典,包含所有的cookie。键和值都为字符串。
def temp(request): print(request.COOKIES) return render(request,"temp.html") #{'csrftoken': 'MB6zspinV3T4wy74bMcSigR6rWoYvabQyL6jo5aTeEDGZenJ74ujHtq7Yx6FKRWq', 'Hm_lvt_da613541f2704950dc2bfc647cfea191': '1560417988'}
HttpRequest.FILES
一个类似于字典的对象,包含所有的上传文件信息。FILES 中的每个键为 中的name,值则为对应的数据。注意,FILES 只有在请求的方法为POST 且提交的
HttpRequest.META
一个标准的Python 字典,包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器,
一个标准的Python 字典,包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器,下面是一些示例: CONTENT_LENGTH —— 请求的正文的长度(是一个字符串)。 CONTENT_TYPE —— 请求的正文的MIME 类型。 HTTP_ACCEPT —— 响应可接收的Content-Type。 HTTP_ACCEPT_ENCODING —— 响应可接收的编码。 HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。 HTTP_HOST —— 客服端发送的HTTP Host 头部。 HTTP_REFERER —— Referring 页面。 HTTP_USER_AGENT —— 客户端的user-agent 字符串。 QUERY_STRING —— 单个字符串形式的查询字符串(未解析过的形式)。 REMOTE_ADDR —— 客户端的IP 地址。 REMOTE_HOST —— 客户端的主机名。 REMOTE_USER —— 服务器认证后的用户。 REQUEST_METHOD —— 一个字符串,例如"GET" 或"POST"。 SERVER_NAME —— 服务器的主机名。 SERVER_PORT —— 服务器的端口(是一个字符串)。 从上面可以看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 之外,请求中的任何 HTTP 首部转换为 META 的键时, 都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_ 前缀。 所以,一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。
def temp(request): print(request.META) return render(request,"temp.html") #一个字典附带一大堆信息
HttpRequest.user
一个 AUTH_USER_MODEL 类型的对象,表示当前登录的用户。
如果用户当前没有登录,user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。
def temp(request): temp = request.user print(temp) print(temp.is_authenticated()) return render(request,"temp.html") # AnonymousUser #False
HttpRequest.session
一个既可读又可写的类似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。完整的细节参见会话的文档。
def temp(request): print(request.session) return render(request,"temp.html") # <django.contrib.sessions.backends.db.SessionStore object at 0x0000018605FCC588>
3.方法
HttpRequest.get_host()
根据从HTTP_X_FORWARDED_HOST(如果打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。如果这两个头部没有提供相应的值,则使用SERVER_NAME 和SERVER_PORT,在PEP 3333 中有详细描述。USE_X_FORWARDED_HOST:一个布尔值,用于指定是否优先使用 X-Forwarded-Host 首部,仅在代理设置了该首部的情况下,才可以被使用。
注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。
def temp(request): print(request.get_host()) return render(request,"temp.html") # 127.0.0.1:8000
HttpRequest.get_full_path()
返回 path,如果可以将加上查询字符串。
def temp(request): print(request.get_full_path()) return render(request,"temp.html") # /temp/?id=2&name=3&age=12
HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
- 返回签名过的Cookie 对应的值,如果签名不再合法则返回django.core.signing.BadSignature。
HttpRequest.is_secure()
如果请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。
def temp(request): print(request.is_secure()) return render(request,"temp.html") # False
HttpRequest.is_ajax()
如果请求是通过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'。
def temp(request): print(request.is_ajax()) return render(request,"temp.html") # False
3.Response对象
- 与由Django自动创建的HttpRequest对象相比,HttpResponse对象是我们的职责范围了。我们写的每个视图都需要实例化,填充和返回一个HttpResponse。
1.使用
#传递字符串 from django.http import HttpResponse response = HttpResponse("Here's the text of the Web page.") response = HttpResponse("Text only, please.", content_type="text/plain")
#设置删除响应头信息 response = HttpResponse() response['Content-Type'] = 'text/html; charset=GBK' del response['Content-Type']
2.属性
HttpResponse.content:响应内容
HttpResponse.charset:响应内容的编码
HttpResponse.status_code:响应的状态码
def temp(request): response = HttpResponse("Text only, please.", content_type="text/plain") response["Content-Type"] = "text/html;charset=GBK" print(response.content)#b'Text only, please.' print(response.charset)#GBK print(response.status_code)#200 return response
4.JsonResponse对象
JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。
from django.http import JsonResponse response = JsonResponse({'foo': 'bar'}) print(response.content) b'{"foo": "bar"}'
默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。
response = JsonResponse([1, 2, 3], safe=False)
例题:
from django.http.response import JsonResponse import json def temp(request): data = {'name': 'alex', 'age': 73} ret = HttpResponse(json.dumps(data)) ret['Content-Type'] = 'application/json' return ret
5.render()
- 结合一个给定的模版和一个给定上下文字典,并返回一个渲染后 HttpResponse 对象
- 参数:
- request: 用于生成响应的请求对象。
- template_name:要使用的模板的完整名称,可选的参数
- context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。
- content_type:生成的文档要使用的MIME类型。默认为 DEFAULT_CONTENT_TYPE 设置的值。默认为'text/html'
- status:响应的状态码。默认为200。
- useing: 用于加载模板的模板引擎的名称。
from django.shortcuts import render def my_view(request): # 视图的代码写在这里 return render(request, 'myapp/index.html', {'foo': 'bar'})
6.redirect()
- 参数可以是:
- 一个模型:将调用模型的
get_absolute_url()
函数 - 一个视图,可以带有参数:将使用
urlresolvers.reverse
来反向解析名称 - 一个绝对的或相对的URL,将原封不动的作为重定向的位置。
- 一个模型:将调用模型的
- 默认返回一个临时的重定向;传递
permanent=True
可以返回一个永久的重定向。 - 默认情况下,
redirect()
返回一个临时重定向。以上所有的形式都接收一个permanent
参数;如果设置为True
,将返回一个永久的重定向:
def my_view(request): ... object = MyModel.objects.get(...) return redirect(object, permanent=True)
扩展阅读:
临时重定向(响应状态码:302)和永久重定向(响应状态码:301)对普通用户来说是没什么区别的,它主要面向的是搜索引擎的机器人。
A页面临时重定向到B页面,那搜索引擎收录的就是A页面。
A页面永久重定向到B页面,那搜索引擎收录的就是B页面。