django 性能优化方案

Django性能优化
本文介绍了解决Django框架中template性能问题的方法,推荐使用jinja2替代原生模板引擎,并提供了两种跟踪Django运行程序的有效手段:使用cProfile进行性能剖析及SQL查询跟踪。
[b][color=red]1.最受不了的就是django和template了,可以说是,慢的不行了[/color]
[/b]
解决方案是使用 jinja2 语法和django相似,性能很好,如图:
[img]http://dl.iteye.com/upload/picture/pic/78158/2ddcf47c-a9cc-365a-b7f1-a472b6801faf.png[/img]


[b][color=red]2.跟踪你的运行程序[/color][/b]
2个方法 Profile 和 Sql跟踪,使用django.middleware方法实现:
cProfile 比Profile高效,代码如下

#encoding = utf-8
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings

class ProfilerMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and 'prof' in request.GET:
self.profiler = cProfile.Profile()
args = (request,) + callback_args
return self.profiler.runcall(callback, *args, **callback_kwargs)

def process_response(self, request, response):
if settings.DEBUG and 'prof' in request.GET:
self.profiler.create_stats()
out = StringIO()
old_stdout, sys.stdout = sys.stdout, out
self.profiler.print_stats("cumulative")
sys.stdout = old_stdout
response.content = '<pre>%s</pre>' % out.getvalue()
return response


Sql跟踪,代码如下

#encoding = utf-8
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings
from django.db import connection
from django.utils.encoding import smart_unicode
import logging
class DatabaseProfilerMiddleware(object):

def process_request(self, request):
pass

def process_response(self, request, response):
if settings.DEBUG and 'sql' in request.GET:
out = StringIO()
out.write('time\tsql\n')
total_time = 0

for query in reversed(sorted(connection.queries, key=lambda x: x['time'])):
total_time += float(query['time'])*1000
try:
out.write(u'<div>%s\t%s\n</div><hr />' % (smart_unicode(query.get('time')), smart_unicode(query.get('sql') ) ))
except Exception,e:
logging.error(e)
response.content = '<pre style="white-space:pre-wrap">%d queries executed in %.3f seconds\n\n%s</pre>' % (len(connection.queries), total_time/1000, out.getvalue())

return response


[/b]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值