如何在django页面请求期间打开文件

时间:2012-08-27 13:36:51

标签: python django django-debug-toolbar

我想优化我的django应用程序,为此,我使用django_debug_toolbar来了解为计算html页面所做的SQL调用。 我想对打开的文件做同样的事情:是否有django_debug_toolbar插件或有没有办法开发django中间件来跟踪html页面请求期间打开的文件?

1 个答案:

答案 0 :(得分:0)

最后我给自己写了一个django中间件:

import __builtin__
def newFileClassFactory(oldfile,openfiles):
    class newfile(oldfile):
        def __init__(self, *args):
            self.thepath = args[0]
            print "### OPENING %s ###" % str(self.thepath)
            try:
                oldfile.__init__(self, *args)
            except Exception,e:
                print e
                raise
            openfiles.add(self.thepath)

        def close(self):
            print "### CLOSING %s ###" % str(self.thepath)
            oldfile.close(self)
            openfiles.remove(self.thepath)
    return newfile

class OpenedFiles(object):
    def __init__(self):
        self.oldfile = __builtin__.file
        self.openfiles = set()
        self.newfile = newFileClassFactory(self.oldfile,self.openfiles) 
        self.oldopen = __builtin__.open
        def newopen(*args):
            return self.newfile(*args)
        self.newopen = newopen

    def process_response(self, request, response):        
        if request.path.split('.')[-1].lower() not in ('ico','jpg','jpeg','gif','png','js','css'):
            if self.openfiles:
                print 'Not closed files :'
                print '----------------'
                print '/n'.join(self.openfiles)
            print '*' * 60,' End of Request (%s)' % request.path            
            __builtin__.file = self.oldfile
            __builtin__.open = self.oldopen
        return response

    def process_request(self, request):
        if request.path.split('.')[-1].lower() not in ('ico','jpg','jpeg','gif','png','js','css'):
            __builtin__.file = self.newfile
            __builtin__.open = self.newopen
            print '*' * 60,' Beginning of Request (%s)' % request.path
        return None

只需在MIDDLEWARE_CLASSES的settings.py中添加'your.module.path.OpenedFiles'(如果你想捕获django在其中间件中执行的操作,则在第一行),所有打开的文件将在运行django时打印在控制台上内置服务器(python manage.py runserver) 它还会打印出现的错误和未关闭的文件。

很有趣的是,django或应用程序打开了许多本地文件来生成动态页面(模板,会话文件,缓存信息,图像以生成动态缩略图......)