Django进阶(路由系统、中间件、缓存、Cookie和Session、Ajax发送数据
路由系统
1、每个路由规则对应一个view中的函数
url(r'^index/(\d*)', views.index), url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage), url(r'^manage/(?P<name>\w*)', views.manage,{'id':333}),
2、根据app对路由规则进行一次分类
rl(r'^web/',include('web.urls')),
1、每个路由规则对应一个view中的函数
2、根据app对路由规则进行一次分类
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327230359854-347956012.png)
django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件,如下图。
中间件中可以定义四个方法,分别是:
- process_request(self,request)
- process_view(self, request, callback, callback_args, callback_kwargs)
- process_exception(self, request, exception)
- process_response(self, request, response)
自定义中间件
1、创建中间件类
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327230401011-1478742894.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327230401604-1783930827.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327230401839-2077963415.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327230402198-1413447692.png)
缓存
由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者Redis中,5分钟内再有人来访问时,则不再去执行view中的操作,而是直接从内存或者Redis中之前缓存的内容拿到,并返回,
1
2
3
4
5
6
7
8
9
10
|
CACHES = { 'default' : { 'BACKEND' : 'django.core.cache.backends.filebased.FileBasedCache' , 'LOCATION' : os.path.join(BASE_DIR, 'cache' ), 'TIMEOUT' : 600 , 'OPTIONS' : { 'MAX_ENTRIES' : 1000 } } } |
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327231400511-2124415813.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327231511995-171521284.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327231518729-15095670.png)
更多参考资料:
https://docs.djangoproject.com/en/1.9/topics/cache/
http://djangobook.py3k.cn/2.0/chapter15/
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: '/' });
cookie保存时间
cookie默认在浏览器中保存 1209600秒,
设置cookie保存时间,在setting.py
SESSION_COOKIE_AGE = 10秒
关闭即失效
设置后,关闭浏览器,cookie即失效
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
二、操作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失效策略。
#'django.middleware.csrf.CsrfViewMiddleware',
python manage.py makemigrations
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232814245-87662680.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232819464-225152019.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232824214-2145651318.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232901417-696386047.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232910401-888110810.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232931464-2105061110.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327232942417-1690701890.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233113261-447565064.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233118792-1401639085.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233123120-127912824.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233133089-205012428.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233138839-1103152070.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327234220870-95162704.png)
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327234226136-2054754965.png)
<body> <table border="1"> <thead> <tr> <th>主机</th><th>端口</th> </tr> </thead> <tbody id="tb01"> <tr> <td>10.0.0.1</td><td>22</td> </tr> </tbody> </table> <input type="button" onclick="AjaxSubmit();" value="Ajax提交"> <script src="/static/jquery-1.11.1.min.js"></script> <script> function AjaxSubmit(){ var host = '10.0.0.1' {#通过js获取表格中的数据#} var port = '22' $.ajax({ url:'/ajax_data/', type:'POST', data:{h:host,p:port}, success:function(arg){} }); }; </script> </body>
成功接收到ajax提交的数据
def index(request): return render(request,'index.html') import json def ajax_data(request): ret = {'status':True,'error':''} try: print request.POST except Exception,e: #异常处理 ret['status'] = False ret['error'] = str(e) return HttpResponse(json.dumps(ret)) #默认只能发送字符串,用json把字典转换成字符穿
<script> function AjaxSubmit(){ var user_list = [ {'username':'yangmv','age':18}, {'username':'wj','age':28}, ] $.ajax({ url:'/ajax_data/', type:'POST', tradition:true, {#对数据原生处理,不做加工#} data:{data:JSON.stringify(user_list)}, {#以字符串的方式#} success:function(arg){ //json.loads var callback_dict = $.parseJSON(arg); {#把返回的数据json.load成字典#} if(callback_dict.status){ alert('成功'); }else{ alert(callback_dict.error); } } }); }; </script>
成功获取到字典数据。并返回执行结果
<body> <p>上传实例</p> <form action="/upload/" method="POST" enctype="multipart/form-data"> <p><input type="file" name="f1" /></p> <p><input type="text" name="hostname" /></p> <input type="submit" value="提交" /> </form> </body> #enctype="multipart/form-data" 是指分片上传
def upload(request): if request.method == "POST": #inp_post = request.POST #捕获提交来的数据 inp_file = request.FILES #捕获提交来的文件数据 get_file = inp_file.get('f1') #print get_file.name #获取上传文件的文件名 #print get_file.size #获取上传文件的大小 f_obj = open(get_file.name,'wb') for line in get_file.chunks(): f_obj.write(line) f_obj.close() return render(request,'home/upload.html')
效果:
![](https://images2015.cnblogs.com/blog/884635/201603/884635-20160327233612964-100057657.png)