通过 jinja2 在烧瓶模板中打印消息除外

Printing except messages in flask templates via jinja2

我创建了一个连接到数据库的函数,如果没有建立连接,它会打印 'failure to connect to db' 消息:

  def connectToDB():
        connectionString = 'dbname=reportingdb1 user=red_gui password=RadnfgoInd host=10.100.51.42'
  try:
     return psycopg2.connect(connectionString)
  except:
     print ("Failure to connect to db")

在我的索引部分的 views.py 文件中,当我故意使用错误的数据库凭证(用于测试目的)。

 ####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
          connectToDB()
          form = StaffNames()
          if form.validate_on_submit():
                  return redirect('/results')
          return render_template('index.html',title='Search Page',form=form)

我的问题是,我希望将此消息打印在网页上。我试过使用 return 而不是 print,但没有用。我还尝试尝试将 except 消息存储在一个变量中,然后在我的 templates/index.html 文件中,通过我尝试过的 jinja2 curly brackets.For 示例调用它: 在 views.py

except:
     noconnect = "Failure to connect to db"

然后在我的 index.html:

{{ noconnect }}

但这也没有奏效。这样做的最佳做法是什么? 谢谢

Web 框架通常需要通过上下文将对象传递给视图和模板。您必须传入 render_template:

中的对象
. . .

error = connectToDB()

return render_template('index.html', title='Search Page',
                       form=form, error=error)

然后在您的模板中,使用:{{ error }}

另一种更像 Django 的方法是为您的数据创建字典:

error = 'error message'
test = 'test'

. . .

data = {
    'error': error,
    'test': test
}

然后 return 你的 render_template 像这样:

return render_template('index.html', title='Search Page',
                       form=form, **data)

双星成功了,所以你仍然可以这样做:{{ error }}。否则,您将不得不这样做:{{ data.error }}

简化 connectToDB 以便它只连接到数据库而不是其他任何东西。

def connectToDB():
    connectionString = 'dbname=reportingdb1 user=red_gui password=RadnfgoInd host=10.100.51.42'
    psycopg2.connect(connectionString)

处理视图中的任何潜在异常(但请注意,捕获 所有 异常不是一个好的做法)。

 ####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    exception = None
    try:
        connectToDB()
    except:
        exception = 'Failure to connect to db'

    form = StaffNames()
    if not exception:
        if form.validate_on_submit():
            return redirect('/results')

    return render_template('index.html',title='Search Page', form=form, exception=exception)

{{ exception }} 放在您的 index.html

中的某处