部署Django API至Google App Engine遇MySQL主机未知错误求助
Hey Jimmy, let's work through this MySQL host error you're hitting when accessing your /products endpoint on Google App Engine. I’ve dealt with nearly identical issues deploying Django apps to GAE with Cloud SQL, so here’s a step-by-step breakdown of what to check:
1. Fix the Database Host Path in Django Settings
The error says it can’t resolve mythic-plexus-194517:europe-west1:giftwiz-api as a MySQL host—and that’s because in GAE’s standard environment, you don’t use the raw instance connection name directly. You need to prefix it with the Cloud SQL Unix socket path: /cloudsql/.
Update your production DATABASES config in settings.py to look like this:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', # Replace with your actual DB name 'USER': 'your_db_username', # Replace with your DB user 'PASSWORD': 'your_db_password',# Replace with your DB password 'HOST': '/cloudsql/mythic-plexus-194517:europe-west1:giftwiz-api', 'PORT': '3306', } }
If you’re using environment variables to separate dev/prod configs, make sure the production host value includes that critical /cloudsql/ prefix.
2. Verify App.yaml Configuration
GAE needs explicit instructions to connect to your Cloud SQL instance. Add these lines to your app.yaml file:
beta_settings: cloud_sql_instances: mythic-plexus-194517:europe-west1:giftwiz-api
This tells GAE to establish a connection to your Cloud SQL instance when deploying your app.
3. Check Cloud SQL Admin API is Enabled
Your Google Cloud project must have the Cloud SQL Admin API enabled for GAE to communicate with the database. To confirm:
- Go to the Google Cloud Console
- Search for "Cloud SQL Admin API"
- If it’s marked as "Disabled", click "Enable"
4. Ensure GAE Service Account Has Correct Permissions
The default GAE service account ([your-project-id]@appspot.gserviceaccount.com) needs the Cloud SQL Client role to access your instance. Here’s how to add it:
- Go to IAM & Admin > IAM in the Cloud Console
- Find the GAE service account in the list
- Click "Edit" > "Add another role"
- Search for "Cloud SQL Client" and select it
- Save the changes
5. Confirm MySQL Driver is Installed
Make sure your requirements.txt includes a valid MySQL driver for Django. The most reliable option is:
mysqlclient>=2.2.0
Avoid using pymysql unless you’ve configured Django to use it as a drop-in replacement (since it can cause subtle connection issues in production).
After making these changes, redeploy your app with gcloud app deploy and test the /products endpoint again. The host resolution error should be gone once the socket path and permissions are correctly set up.
内容的提问来源于stack exchange,提问作者jimmygoldshine

