django第四天
###中间件
- 浏览器
- wsgi Web服务器网关接口 Web Server Gateway Interface
- middleware 中间件
- process_request(self, request)
- 参数
- request 请求对象
- 在路由和视图函数执行之前
- 中间件根据注册的先后,顺序执行
- 返回值为None 正常流程
- 返回HttpResponse,则不会继续走中间件后面的类,也不会走路由和视图函数,直接返回给浏览器
- process_response(self, request, response)
- 参数
- request 请求对象
- response 响应对象
- 在路由和视图函数执行之后
- 中间件根据注册的先后,倒序执行
- 返回值为None 会报错
- 直接返回response对象
- process_view(self, request, view_func, view_args, view_kwargs)
- 参数
- request 请求对象
- view_func 视图函数
- view_args 视图函数的位置参数
- view_kwargs 视图函数的关键字参数
- 在视图函数执行前,在路由执行后
- 中间件根据注册的先后,顺序执行
- 返回值为None 正常流程
- 返回HttpResponse,会从最后一个process_response开始执行,然后返回给浏览器
- process_exception(self, request, exception)
- 参数
- request 请求对象
- exception 异常对象
- 在视图函数出错时执行
- 中间件根据注册的先后,倒序执行
- 返回值为None 正常流程
- 返回HttpResponse, 不在继续执行后续的中间件中的process_exception方法
直接返回到最后一个process_response方法,然后返回给浏览器。
- process_template_response(self, request, response)
- 参数
- request 请求对象
- response 响应对象
- 在视图函数调用TemplateResponse时执行
- 中间件根据注册的先后,倒序执行
- 返回Response对象
- my_middlewares.py
```python
# -*- coding: utf-8 -*-
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class MD1(MiddlewareMixin):
def process_request(self, request):
print("process_request MD1")
# return HttpResponse('md1')
def process_response(self, request, response):
print("process_response MD1")
return response
def process_view(self, request, view_func, view_args, view_kwargs):
print("process_view MD1")
# return HttpResponse("process_view MD1")
def process_exception(self, request, exception):
print("process_exception MD1")
print(exception, "MD1")
def process_template_response(self, request, response):
print("process_template_response MD1")
return response
class MD2(MiddlewareMixin):
def process_request(self, request):
print("process_request MD2")
def process_response(self, request, response):
print("process_response MD2")
return response
def process_view(self, request, view_func, view_args, view_kwargs):
print("process_view MD2")
# return HttpResponse("process_view MD2")
def process_exception(self, request, exception):
print("process exception MD2")
print(exception, "MD2")
def process_template_response(self, request, response):
print("process_template_response MD2")
return response
class MD3(MiddlewareMixin):
def process_request(self, request):
print("process_request MD3")
def process_response(self, request, response):
print("process_response MD3")
return response
def process_view(self, request, view_func, view_args, view_kwargs):
print("process_view MD3")
# return HttpResponse("process_view MD3")
def process_exception(self, request, exception):
print("process_exception MD3")
print(exception, "MD3")
# return HttpResponse(exception)
def process_template_response(self, request, response):
print("process_template_response MD3")
response.template_name = "index1.html"
response.context_data['name'] = 'lucy'
return response
```
- settings.py
```python
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
'app01.my_middlewares.MD1',
'app01.my_middlewares.MD2',
'app01.my_middlewares.MD3',
]
```
- url路由表
- views视图函数
- orm 数据库表(类)
- template 模板
###JSON是什么?
- JSON指的是JavaScript对象表示法(JavaScript Object Notation)
- JSON是轻量级的文本数据交换格式
- JSON独立于语言
- JSON具有自我描述性,更易理解
- 属性名必须使用双引号
- 不能使用十六进制作为属性值
- 不能使用undefined作为属性值
- 不能使用函数和日期对象作为属性值
###Javascript对象和JSON的转化
```javascript
test_obj = {'name':'lily'}
//Object { name: "lily" }
test_json = JSON.stringify(test_obj)
//"{\"name\":\"lily\"}"
test_obj = JSON.parse(test_json)
//Object { name: "lily" }
```
###AJAX 异步的Javascript和Xml (Asynchnorous Javascript And Xml)
###通过form表单提交实现算术运算
```html
<form action="" method="post">
<p>
{% csrf_token %}
<input type="text" name="num1" value="{{ num1 }}"> +
<input type="text" name="num2" value="{{ num2 }}"> =
<input type="text" name="num3" value="{{ num3 }}">
<button>计算</button>
</p>
<p>
<input type="text" name="num11" value="{{ num11 }}"> +
<input type="text" name="num22" value="{{ num22 }}"> =
<input type="text" name="num33" value="{{ num33 }}">
<input type="button" id="btn_id" value="计算">
</p>
<p>
<input type="button" id="btn1" value="Ajax测试">
</p>
</form>
```
```python
from django.shortcuts import render
def calc(request):
if request.method == 'POST':
num1 = request.POST.get('num1')
num2 = request.POST.get('num2')
num3 = int(num1) + int(num2)
return render(request, 'calc.html', {'num1': num1, 'num2': num2, 'num3': num3})
return render(request, 'calc.html')
```
###通过Ajax实现算术运算
```javascript
$("#btn_id").click(function () {
var num1 = $("input[name='num11']").val();
var num2 = $("input[name='num22']").val();
$.ajax({
url: '/calc/',
type: 'post',
data: {
num1: num1,
num2: num2,
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val(),
},
success: function (ret) {
$("input[name='num33']").val(ret);
console.log(ret);
},
error: function (ret) {
console.log(ret);
}
});
});
```
```python
from django.shortcuts import render, HttpResponse
def calc(request):
if request.method == 'POST':
num1 = request.POST.get('num1')
num2 = request.POST.get('num2')
num3 = int(num1) + int(num2)
return HttpResponse(num3)
return render(request, 'calc.html')
```
###Ajax局部提交参数中含有数组(序列化和反序列化)
```html
<button id="btn1">Ajax测试</button>
```
```javascript
$("#btn1").click(function () {
$.ajax({
url: '/test/',
type: 'post',
headers:{"X-CSRFTOKEN": $.cookie('csrftoken')},
data: {
name: 'lily',
age: 18,
hobby: JSON.stringify(["爬山", "打羽毛球", "打乒乓球"])
},
success: function (ret) {
console.log(ret);
},
error: function (ret) {
console.log(ret);
}
});
});
```
```python
from django.http.response import JsonResponse
import json
def test(request):
if request.method == "POST":
name = request.POST.get('name')
age = request.POST.get('age')
hobby = json.loads(request.POST.get('hobby'))
print("name:", name, type(name)) # name: lily <class 'str'>
print("age:", age, type(age)) # age: 18 <class 'str'>
print("hobby:", hobby, type(hobby)) # hobby: ['爬山', '打羽毛球', '打乒乓球'] <class 'list'>
return JsonResponse({"status": "success", "code": 200})
```
###Ajax局部提交(参数中含有数组)
```html
<button id="btn2">Ajax测试2</button>
```
```javascript
$("#btn2").click(function () {
$.ajax({
url: '/test2/',
type: 'post',
data: {
name: 'lily',
age: 18,
hobby: ["爬山", "打羽毛球", "打乒乓球"]
},
success: function (ret) {
console.log(ret);
},
error: function (ret) {
console.log(ret);
}
});
});
```
```python
from django.http.response import JsonResponse
def test2(request):
if request.method == "POST":
name = request.POST.get('name')
age = request.POST.get('age')
hobby = request.POST.get('hobby')
hobby2 = request.POST.get('hobby[]')
hobby3 = request.POST.getlist('hobby[]')
print("name:", name, type(name)) # name: lily <class 'str'>
print("age:", age, type(age)) # age: 18 <class 'str'>
print("hobby:", hobby, type(hobby)) # hobby: None <class 'NoneType'>
print("hobby2:", hobby2, type(hobby2)) # hobby2: 打乒乓球 <class 'str'>
print("hobby3:", hobby3, type(hobby3)) # hobby3: ['爬山', '打羽毛球', '打乒乓球'] <class 'list'>
return JsonResponse({"status": "success", "code": 200})
```
###Ajax实现上传文件
```html
<input type="file" name="f1">
<button id="file_upload">上传</button>
```
```javascript
$("#file_upload").click(function () {
var form_data = new FormData();
form_data.append('f1', $("input[name='f1']")[0].files[0] );
$.ajax({
url: '/upload/',
type: 'post',
processData: false, //告诉Jquery不处理数据
contentType: false, //告诉Jquery不处理请求头信息
data: form_data,
success: function (ret) {
console.log(ret);
},
error: function (ret) {
console.log(ret);
}
});
});
```
```python
from django.http.response import render,JsonResponse
def upload(request):
if request.method == "POST":
file_obj = request.FILES.get('f1')
with open(file_obj.name, "wb") as f:
for con in file_obj:
f.write(con)
return JsonResponse({"status": "success", "code": 200})
return render(request, 'calc.html')
```
###form表单实现上传文件
```html
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="ff1">
<button>上传</button>
</form>
```
```python
from django.http.response import JsonResponse, render
def calc(request):
if request.method == "POST":
file_obj = request.FILES['ff1']
with open(file_obj.name, "wb") as f:
for con in file_obj:
f.write(con)
return JsonResponse({"status": "success", "code": 200})
return render(request, 'calc.html')
```
###局部开启csrf_token,只需要给视图函数添加csrf_protect装饰器
```python
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def calc(request):
if request.method == "POST":
pass
```
###局部关闭csrf_token,只需要给视图函数添加csrf_exempt装饰器
```python
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def calc(request):
if request.method == "POST":
pass
```
###强制设置cookie,只需要给视图函数增加ensure_csrf_cookie
```python
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def calc(request):
if request.method == "POST":
pass
```