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

2024-09-30 22:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个连接到数据库的函数,如果没有连接到数据库,它会打印“连接到数据库失败”消息:

  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")

在我的视图.py在index部分中,这个函数被直接调用,并且在我的测试环境中,当我故意为数据库使用错误的凭证时(出于测试目的),会将except failure语句打印到我的终端中。在

^{pr2}$

我的问题是,我想把这条信息打印在网页上。我试过用return代替print,但是没有用。我还尝试将except消息存储在变量中,然后存储在模板中/索引.html文件,通过jinja2 curly呼叫它括号。用于我试过的例子: 在视图.py在

except:
     noconnect = "Failure to connect to db"

然后在我的索引.html公司名称:

{{ noconnect }}

但这也没用。最好的做法是什么? 谢谢


Tags: to函数py视图数据库消息dbreturn
2条回答

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

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

处理视图中的任何潜在异常(但是要注意,捕捉所有异常并不是一个好的实践)。在

^{pr2}$

{{ exception }}放在你的index.html的某个地方

Web框架通常要求对象通过上下文传递到视图和模板。必须传入render_template中的对象:

. . .

error = connectToDB()

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

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

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

^{pr2}$

然后返回您的render_template,如下所示:

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

双星使得你仍然可以这样做:{{ error }}。否则,您必须这样做:{{ data.error }}

相关问题 更多 >