2016-08-18 64 views
2

在调试时,通过浏览器中的“查看源代码”菜单项查看呈现的HTML和JS模板非常有用,但这样做会迫使用户使用浏览器的UI。在调试过程中,Flask/Jinja2是否提供了保存呈现的模板?

Jinja2(或Flask)是否提供了一个工具来保存服务器上最后n个渲染模板?然后可以使用自己喜欢的编辑器查看渲染文件,并使用自己熟悉的字体锁定和搜索功能。

手工实现这样的设施当然是可能的,但是这样做太过分了,就像在使用打印语句进行调试时胡乱写一个程序一样,这种方法不能缩放。我正在寻找一个更好的选择。

回答

1

我认为最简单的做法是使用after_request钩子。

from flask import g 
@main.route('/') 
def index(): 
    models = Model.query.all() 
    g.template = 'index' 
    return render_template('index.html', models=models) 


@main.after_request 
def store_template(response): 
    if hasattr(g, 'template'): 
     with open('debug/{0}-{1}'.format(datetime.now(), g.template), 'w') as f: 
      f.write(response.data) 
    return response 

这里是文档。 http://flask.pocoo.org/snippets/53/

只要收集最后一个n模板,我可能会设置一个cron作业来做到这一点。下面是一个例子

import os 
from datetime import datetime 

def make_files(n): 
    text = ''' 
    <html> 
    </html> 
    ''' 

    for a in range(n): 
     with open('debug/index-{0}.html'.format(datetime.now()), 'w') as f: 
      f.write(text) 

def get_files(dir): 
    return [file for file in os.listdir(dir) if file.endswith('.html')] 

def delete_files(dir, files, amount_kept): 
    rev = files[::-1] 
    for file in rev[amount_kept:]: 
     loc = dir + '/' + file 
     os.remove(loc) 

if __name__ == '__main__': 
    make_files(7) 
    files = get_files('debug') 
    print files 
    delete_files('debug', files, 5) 
    files = get_files('debug') 
    print files 

编辑

删除功能中的文件的顺序相反,因此将保持最近使用的文件。也无法找到访问原始模板名称以避免硬编码的方式。

EDIT 2

好吧,所以其更新为您展示如何使用flask.g模板名称传递给after_request功能

文档http://flask.pocoo.org/docs/0.11/testing/#faking-resources

+0

好问题,好答案。我建议的一个改变是使用Python日志记录;那么你可以配置多少次日志的控制,并且你可以使用RotatingFileHandler。 https://docs.python.org/2/library/logging.handlers.html#rotatingfilehandler –

+0

唯一的问题是区分模板。我会尽力弄清楚。 – Adam

+0

当你创建记录器时,你可以给他们名字,这将有助于。 –