Reputation: 1569
I am a newbie in python. I need to access a python file from another file in another directory. In particular I want to be able to see these database details which are in a file named settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dynamic',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '192.168.10.130',
}
}
How do I access this dictionary as a database from another file in another folder?
I have tried to do it like this (which works in my other project):
from django.conf import settings
dbHost = settings.DATABASES['default']['HOST']
dbUsername = settings.DATABASES['default']['USER']
dbPassword = settings.DATABASES['default']['PASSWORD']
dbName = settings.DATABASES['default']['NAME']
Please help me. Thanks in advance.
Upvotes: 6
Views: 7389
Reputation: 6276
from django.conf import settings
settings.DATABASES
{'default':
{'ATOMIC_REQUESTS': False,
'AUTOCOMMIT': True,
'CONN_MAX_AGE': 3600,
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'NAME': 'proj',
'OPTIONS': {'charset': 'utf8', 'sql_mode': 'traditional'},
'PASSWORD': 'password',
'PORT': '20306',
'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None},
'TIME_ZONE': None,
'USER': 'root'}
}
Upvotes: 2
Reputation: 2347
If you want to use projectA.settings.DATABASES
in projectB then you should add projectA path in projectB:
projectB/myfile.py:
import sys
sys.path.append( "/path/to/projectA" )
from projectA import settings
dbHost = settings.DATABASES['default']['HOST']
dbUsername = settings.DATABASES['default']['USER']
dbPassword = settings.DATABASES['default']['PASSWORD']
dbName = settings.DATABASES['default']['NAME']
Upvotes: 5
Reputation: 4422
Inside the settings.py of project 2, you can import project1 settings file as:
import project1.settings
and then initialize the DATABASES as:
DATABASES = { 'default': project1.settings.DATABASES['default'] }
Upvotes: 1
Reputation: 30472
Instead of hard coding your credentials in python, you can use dj-database-url to easily load DB settings from an environment variable.
Another option would be using json.load()
and a small json file.
Upvotes: 1