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
132 views
in Technique[技术] by (71.8m points)

python 3.x - Django Ignoring Remote MYSQL connection details

I have a Django Rest Framework application working as expected with a local MySQL Database however, when I attempt to connect to a remote MySQL server I keep getting the following error:

Access denied for user 'my_user'@'localhost

Note the @ localhost, this is odd as I'm specifying a REMOTE MySQL Host. In my settings.py I have the following database configuration:

DATABASES = {}
DATABASES['user'] = {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': os.environ['DATABASE_NAME'],
           'USER': os.environ['DATABASE_USERNAME'],
           'PASSWORD': os.environ['DATABASE_PASSWORD'],
           'HOST:': os.environ['DATABASE_HOST'],  # this is a remote host!
           'PORT': os.environ['DATABASE_PORT'],
           
       }

As you can see I'm populating the parameters via explicit environment variable values. The HOST argument points to db4free.net (I have a test database located there). Thus I'm not sure why Django continues to attempt to connect to a database on localhost.

question from:https://stackoverflow.com/questions/66064484/django-ignoring-remote-mysql-connection-details

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

1 Reply

0 votes
by (71.8m points)

Solved the issue. I've elected to post what I did to resolve the error in the hope that it may serve as some assistance to others that encounter this issue and indeed stumble across this post in an attempt to realise a prompt resolution:

So, in a nutshell, it would seem that there was some issue with the default Django MySQL driver that was, in turn, preventing remote connections from being established. To resolve this I (pip) installed this tool: https://github.com/jacobian/dj-database-url which acts as a wrapper around various database drivers. I then proceeded to import the utility to my settings.py and updated the DATABASE variable assignment to read as follows:

DATABASES['default'] = dj_database_url.config(default='mysql://'+os.environ['DATABASE_USERNAME']+':'+os.environ['DATABASE_PASSWORD']+'@'+os.environ['DATABASE_HOST']+':'+os.environ['DATABASE_PORT']+'/'+os.environ['DATABASE_NAME'])

notice the use of dj_database_url.config in place of the direct dictionary based assignment prior. After making this change, both local and remote database connections were able to be successfully established.


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

1.4m articles

1.4m replys

5 comments

56.9k users

...