Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

python - How to know current name of the database in Django?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get the db name with recent Django versions (tried with 1.8):

from django.db import connection
db_name = connection.settings_dict['NAME']
# Or alternatively
# db_name = connection.get_connection_params()['db']

Be mindful of reading this value after initialization, so that it has the correct value when running unit tests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...