如何在Django中测试数据库连接? [英] How do I test a database connection in Django?
问题描述
如何测试Django的数据库连接?例如,确保数据库的用户名和密码正确。
How do I test a database connection for Django? For example to make sure that the username and password of the database is correct.
或者如果更容易,当数据库连接失败时,我在哪里捕获数据库错误?
Or if it is easier, where do I "catch" the database error when database connection fails ?
我有一种场景,数据库连接参数以用户的形式定义。我需要确保用户名/密码正确,数据库必须连接成功才能继续。
I have a scenario where database connection parameters is defined in a form by user. I need to make sure the username/password is correct and database must connect successfully before proceeding.
我似乎没有找到任何文档,因为大多数文章认为数据库连接总是成功的。
I can't seem to find any documentation anywhere, as most articles assume that the database connection is always successful.
提前感谢
推荐答案
撰写中间件(Django如何处理请求),它将检查数据库连接并重定向到编辑表单。
Write a middleware ("How Django processes a request") which will check for the database connection and redirect to your edit form.
class DbCheckMiddleware(object):
def process_request(self, request):
try:
"Some DB Code"
success = True
except:
success = False
request.db_connection_successful = success
缓存db_connection_successful用于性能。
Cache 'db_connection_successful' for performance.
这篇关于如何在Django中测试数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!