简体   繁体   中英

Connect to remote mysql with django on Windows 10

I've got a Django settings file which works on mac and linux which will let me use my. my.cnf file to connect to a remote MySQL database on AWS. However, on Windows 10 this doesn't seem to be the case. It keeps on saying it can't connect to the local database as if the my.cnf file doesn't exist.

I've installed mysql connector and python mysql connector on windows 10, along with pip install mysqlclient as well like I would need to on linux however the problem still persists.

db_conf = Path("Project/my.cnf")
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '{}'.format(db_conf),
        }
   }
}

With the same settings file I can run makemigrations, migrate and run the server. On windows this same thing crashes it. my.cnf is the same on Windows/Mac/Linux any help would be appreciated.

I suspect it's a hangup with the way Windows does paths but I'm unsure how to resolve this as I usually code in Linux.

I've resolved the issue but..not in the way I wanted. I don't know why but django and windows don't seem to like using os.path or Path when trying to use it to connect to mysql database.

As such I've used a longer winded route using configparser and no longer having django read a config file instead give it the details in the settings file.

import configparser
db_conf = Path("Project/my.cnf")
conf = configparser.ConfigParser()
conf.read(db_conf)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': conf.get("client", "database"),
        'USER': conf.get("client", "user"),
        'PASSWORD': conf.get("client", "password"),
        'HOST': conf.get("client", "host"),
        'PORT': '3306',
    }
}

What I find hilarious about this whole situation is that Path works normally except when trying to read it with django on Windows. It's not the situation I wanted but it does resolve the issue. I hope this helps others who may be struggling doing the same thing when connecting to a remote mysql server on Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM