2016-08-18 44 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

當你創建記錄器時,你可以給他們名字,這將有助於。 –

相關問題