I'm writing tests in my django project. For now, I have two database connections:
(settings.py)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name'
...
},
}
and custom connection to MongoDB:
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
try:
connection = Connection(host="localhost", port=27017)
db = connection['db_name']
print "Connected successfully(Mongo, db_name)"
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
and I want to know when my project is running through
python manage.py test myapp
Because when you run tests, django automatically create separate DB(with name like test_db_name), but in this case Mongo will still run with db_name. I tried:
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
from django.db import connections
try:
connection = Connection(host="localhost", port=27017)
db_name = connections['default'].settings_dict['NAME']
db = connection[db_name]
print "Connected successfully(Mongo, %s)" % (db_name,)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
but it does not work
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…