Django PythonAnywhere (2003, "Can't connect to MySQL server (timed out)")

Question:

I’m trying to setup a Django project and I can’t seem to connect to MySQL database made in PythonAnywhere.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'username$dbname',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'username.mysql.pythonanywhere-services.com',
    }
}

I cant enter the database in the PythonAnywhere Bash with my user, host, name and password, but when i try to do it in django it appears as follows:

django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'username.mysql.pythonanywhere-services.com' (timed out)")

Asked By: João Marcelino

||

Answers:

Add PORT in default database settings.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'username$dbname',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'username.mysql.pythonanywhere-services.com',
        'PORT': '3306'
    }
}
Answered By: Umair Anwar

I couldn’t fix this error.
Installed MySQL Workbench and used localhost to run the database.
After that, I was able to run the following code:

DATABASES = {
     "default": {
         "ENGINE": "django.db.backends.mysql",
         "NAME": "Mysql",
         "USER": "admin",
         "PASSWORD": "password",
         "HOST": "127.0.0.1",
         "PORT": "3306",
    }
 }
Answered By: João Marcelino

Make sure you can connect to the database outside django. E.g.Via Shell or MySQLWorkBench.

Everything was working fine on my home wifi. But I encountered the same error when using a public wifi. It seemed the database provider I used (Azure) blocked the access. When this error occured, Shell connection and MySQLWorkBench would not work as well.

Answered By: StuffedChicken