我创建了一个连接到数据库的函数,如果没有连接到数据库,它会打印“连接到数据库失败”消息:
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 }}
但这也没用。最好的做法是什么? 谢谢
简化
connectToDB
以便它只连接到数据库而不连接其他任何东西。在处理视图中的任何潜在异常(但是要注意,捕捉所有异常并不是一个好的实践)。在
^{pr2}$把
{{ exception }}
放在你的index.html
的某个地方Web框架通常要求对象通过上下文传递到视图和模板。必须传入
render_template
中的对象:然后在模板中,使用:
{{ error }}
另一种更像Django的方法是为数据创建字典:
^{pr2}$然后返回您的
render_template
,如下所示:双星使得你仍然可以这样做:
{{ error }}
。否则,您必须这样做:{{ data.error }}
相关问题 更多 >
编程相关推荐