如何在jinja中检测调试模式?

时间:2015-10-02 09:06:24

标签: python debugging flask jinja2

在烧瓶中,我想根据我们是否处于调试模式,在jinja模板中包含/排除内容。我不是在辩论这是一个好的或坏的想法(我投票'糟糕'但是只想为这个案例做这件事:-),那么这最好的发生怎么样?

我希望我不必将变量明确地传递给模板,不像这样:

CREATE FUNCTION [dbo].[UDF_FulfilmentBatch](@FulfilmentID INT) RETURNS
        @Result TABLE (
                [sequence]  INT,
                membershipid    BIGINT,
                membershipNo    VARCHAR(255)
        IF @FulfilmentID = 4
        BEGIN
        ,Delivery   VARCHAR(255)
        END
        )
        AS
        BEGIN

        DECLARE @_sequence  INT
        DECLARE @_membershipid  BIGINT
        DECLARE @_membershipNo  VARCHAR(255)
IF @FulfilmentID = 4
        BEGIN
        DECLARE @_Delivery  VARCHAR(255)
        END

        SET @_sequence = 1

        IF @FulfilmentID = 4
        BEGIN
            DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
                SELECT * from VW_FulfilmentExtract_HH
        END
    IF @FulfilmentID = 3
        BEGIN
            DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
                SELECT * from VW_FulfilmentExtract_ID
        END
        ELSE IF @FulfilmentID = 2
        BEGIN
            DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
                SELECT * from VW_FulfilmentExtract_Art
        END
        ELSE
            DECLARE FulfilCursor CURSOR FAST_FORWARD FOR 
                SELECT * from VW_FulfilmentExtract_Tha

        OPEN FulfilCursor

        FETCH NEXT FROM FulfilCursor INTO @_membershipid, @_membershipNo

        WHILE @@FETCH_STATUS = 0 BEGIN

            INSERT INTO @Result
            VALUES (@_sequence, @_membershipid, @_membershipNo IF @FulfilmentID=4 BEGIN @_Delivery  )   

            SET @_sequence = @_sequence + 1 

            FETCH NEXT FROM FulfilCursor INTO @_membershipid, @_membershipNo
        END

        CLOSE FulfilCursor
        DEALLOCATE FulfilCursor

        RETURN

        END




        GO

并不是说这太难了,但我宁愿在模板中神奇地说:

render_template('foo.html', debug=app.debug)

是否有一些默认变量只是懒得等待我突袭?

2 个答案:

答案 0 :(得分:10)

使用context processors

  

要将新变量自动注入模板的上下文,Flask中存在上下文处理器。上下文处理器在呈现模板之前运行,并且能够将新值注入模板上下文。上下文处理器是返回字典的函数。然后,对于应用程序中的所有模板,此字典的键和值将与模板上下文合并:

to_char(to_timestamp('2015-08-19 00:00:01.0', 'yyyy-mm-dd hh24:mi:ss.ff'), 'DD-MON-YYYY')

现在可以在模板中访问@app.context_processor def inject_debug(): return dict(debug=app.debug) 变量。

答案 1 :(得分:3)

使用app.run(debug=True)运行烧瓶应用程序时,您也可以像这样检查config对象:

{% if config['DEBUG'] %}
    <h1>My html here</h1>
{% endif %}