注:本篇是Django进阶篇章,适合人群:有Django基础,关于Django基础篇,将在下一章节中补充!
首先我们一起了解下Django整个请求生命周期:
Django 请求流程,生命周期:
路由部分
代码如下:
myWeb中url.py
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
#url(r'^user_list/(\d+)/(\d+)$', views.user_list),
#url(r'^user_list/(?P<v1>(\d+))/(?P<v2>(\d+))$', views.user_list),
#url(r'^$', views.index),
url(r'^app01/',include("app01.urls")),
]
app01中views.py
from django.shortcuts import HttpResponse
def index(request):
return HttpResponse('index')
def user_list(request,v1,v2):
print v1,v2
return HttpResponse(v1+v2)
app01 中url.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^index/$', views.index),
]
访问方法:
http://127.0.0.1:9001/app01/index
可知:这样定义的好处是,在多个app的场合下可以很好的分离出来!
二、中间件
自定义中间件:
思路分析:
1、获取请求
2、去settings.py MIDDLEWARE_CLASSES 中注册
3、注册好后,Django会自动去setttings里找 MIDDLEWARE_CLASSES
4、遍历注册中的类:
for 类 in MIDDLEWARE_CLASSES:
obj = 类()
if obj里有process_request方法:
process_request_list.append(obj.process_request)
for i in process_request_list:
i()
for i in process_view_list:
i()
views.py 中函数:
for i in process_response_list:
i()
...
分析源码截图:
开始自定义中间件,目录结构如下:
middle_ware.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'Allen'
class mid(object):
def process_request(self,request):
print "mid.process_request"
def process_view(self, request, callback, callback_args, callback_kwargs):
print "mid.process_view"
def process_response(self, request, response):
print "mid.process_response"
return response
class ddd(object):
def process_request(self,request):
print "ddd.process_request"
def process_view(self, request, callback, callback_args, callback_kwargs):
print "ddd.process_view"
def process_response(self, request, response):
print "ddd.process_response"
return response
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
def index(request):
print "index"
return HttpResponse('index')
setting.py 进行注册:
MIDDLEWARE_CLASSES = [
#....
'middleware.middle_ware.mid', #注册
'middleware.middle_ware.ddd', #注册
]
访问:
http://127.0.0.1:9001/app01/index
执行结果:
mid.process_request
ddd.process_request
mid.process_view
ddd.process_view
index
ddd.process_response
mid.process_response
cookie和session
cookie 就是一段字符串,保存在本地
session 保存在服务器端
操作Cookie
获取cookie:request.COOKIES[key]
设置cookie:response.set_cookie(key,value)
由于cookie保存在客户端的电脑上,所以,jquery也可以操作cookie。
<script src='/static/js/jquery.cookie.js'></script>
$.cookie("list_pager_num", 30,{ path: '/' });
操作Session
获取session:request.session[key]
设置session:reqeust.session[key] = value
删除session:del request[key]
request.session.set_expiry(value)
如果value是个整数,session会在些秒数后失效。
如果value是个datatime或timedelta,session就会在这个时间后失效。
如果value是0,用户关闭浏览器session就会失效。
如果value是None,session会依赖全局session失效策略。
session 设置失效时间:
setting.py
SESSION_COOKIE_AGE = 1209600 (默认是这么多秒)
我们可以设置1分钟,或者更小,如10秒
SESSION_EXPIRE_AT_BROWSER_CLOSE 设置false (只要浏览器关闭,session自动过期)
示例如下:
views.py
def login(request):
print request.method
if request.method == "POST":
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == "test" and pwd == '123':
request.session['login'] = True
return redirect('/app01/data/')
return render(request,'login.html')
def data(request):
is_login = request.session.get('login',False)
if is_login:
return HttpResponse('login success!')
else:
return redirect('/app01/login/')
app01下的urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^data/', views.data),
url(r'^login/', views.login),
]
setting.py
注释下面的内容:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', #需要注释,否则报错
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#'middleware.middle_ware.mid', #这里是上面的项目,为了效果,我们注释下面两行
#'middleware.middle_ware.ddd',
]
访问:http://127.0.0.1:9001/app01/login/ 用户名和密码分别为:test 123
Django下Form表单
django中的Form一般有两种功能:
1、输入html
2、验证用户输入
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
from django import forms
from django.core.exceptions import ValidationError
def mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
if not mobile_re.match(value):
raise ValidationError('手机号码格式错误')
class PublishForm(forms.Form):
user_type_choice = (
(0, u'普通用户'),
(1, u'高级用户'),
)
user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,
attrs={'class': "form-control"}))
title = forms.CharField(max_length=20,
min_length=5,
error_messages={'required': u'标题不能为空',
'min_length': u'标题最少为5个字符',
'max_length': u'标题最多为20个字符'},
widget=forms.TextInput(attrs={'class': "form-control",
'placeholder': u'标题5-20个字符'}))
memo = forms.CharField(required=False,
max_length=256,
widget=forms.widgets.Textarea(attrs={'class': "form-control no-radius", 'placeholder': u'详细描述', 'rows': 3}))
phone = forms.CharField(validators=[mobile_validate, ],
error_messages={'required': u'手机不能为空'},
widget=forms.TextInput(attrs={'class': "form-control",
'placeholder': u'手机号码'}))
email = forms.EmailField(required=False,
error_messages={'required': u'邮箱不能为空','invalid': u'邮箱格式错误'},
widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))
示例如下:
app01中的urls.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/app01/user_list/" method="post">
<p>用户:{{ obj.user }}<span>{{ errors.user }}</span></p>
<p>性别:{{ obj.sex }}<span>{{ errors.sex }}</span></p>
<p>邮箱:{{ obj.email }}<span>{{ errors.email }}</span></p>
<p>手机{{ obj.mobile }}<span>{{ errors.mobile }}</span></p>
<input type="submit" value="submit"/>
</form>
</body>
</html>
views.py
from django import forms
class UserInfo(forms.Form):
user = forms.CharField()
sex = forms.CharField()
mobile = forms.EmailField()
email = forms.EmailField()
def user_list(request):
obj = UserInfo()
if request.method == "POST":
user_input_obj = UserInfo(request.POST)
if user_input_obj.is_valid():
data = user_input_obj.clean() #获取用户输入的所有内容
print data
else:
error_msg = user_input_obj.errors
return render(request,'user_list.html',{'obj':user_input_obj,'errors':error_msg})
return render(request,'user_list.html',{'obj':obj})
templates中的user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/app01/user_list/" method="post">
<p>用户:{{ obj.user }}<span>{{ errors.user }}</span></p>
<p>性别:{{ obj.sex }}<span>{{ errors.sex }}</span></p>
<p>邮箱:{{ obj.email }}<span>{{ errors.email }}</span></p>
<p>手机{{ obj.mobile }}<span>{{ errors.mobile }}</span></p>
<input type="submit" value="submit"/>
</form>
</body>
</html>
访问:http://127.0.0.1:9001/app01/user_list/
结果截图:from_1.png
提交结果截图2:from_2.png
提交结果截图如下:
ajax
(WUSIR)
function AjaxSubmitSet(){
var array_users= [
{'username': 'alex', 'age': 18},
{'username': 'rain', 'age': 16},
{'username': 'eric', 'age': 17}
];
$.ajax({
url: "/ajax_data_set/",
type: 'POST',
tradition: true,
data: {data: JSON.stringify(array_users)},
success: function(arg){
// json.loads
var callback_dict = $.parseJSON(arg);
if(callback_dict.status){
alert('成功');
}else{
alert(callback_dict.error);
}
}
});
}
import json
def ajax_data_set(request):
ret = {'status': True, 'error':""}
try:
print request.POS
except Exception,e:
ret['status'] = False
ret['error'] = str(e)
return HttpResponse(json.dumps(ret))