`

django 性能优化方案

阅读更多
1.最受不了的就是django和template了,可以说是,慢的不行了

  解决方案是使用 jinja2 语法和django相似,性能很好,如图:



2.跟踪你的运行程序
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]
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics