从 App Engine 连接到 Google Cloud SQL:访问被拒绝

Connecting to Google Cloud SQL from App Engine: access denied

正在尝试从 App Engine 连接到 Google 云 SQL。收到错误 500,日志显示:"Access denied for user 'root'@'cloudsqlproxy~' (using password: NO)")。 App Engine 和云 SQL 在同一个项目中。我用来连接的代码:

class MainPage(webapp2.RequestHandler):

def get(self):

    self.response.headers['Content-Type'] = 'text/plain'

    env = os.getenv('SERVER_SOFTWARE')
    if (env and env.startswith('Google App Engine/')):
        # Connecting from App Engine
        db = MySQLdb.connect(
            unix_socket='/cloudsql/<project-id>:europe-west1:<instance-name>',
            user='root')

    cursor = db.cursor()
    cursor.execute('SELECT 1 + 1')

    self.response.write('pong')

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

据我所知,我做的一切都是正确的。上面的代码我有效地复制粘贴了一个片段,您可以在 Google Dev Console 中查看它。 StackExchange 上到处都说我不应该传递密码,所以我也没有这样做。我在创建实例时更改了 root 用户密码。我不明白为什么数据库会拒绝访问 App Engine,它们在同一个项目中!有没有办法检查数据库的权限是什么?

好吧,原来是有一些误传发生了。添加密码参数解决了我的问题。但是由于某些原因,Google 文档中没有提及这一点,而 Whosebug 上的许多帖子实际上直接告诉您相反的说法,如果您在登录时向其传递密码,Cloud SQL 将抛出错误来自 AppEngine。也许最近的一些更新是导致此问题的原因,但就我而言,传递密码解决了问题。希望对您有所帮助!

我想说这部分在 Google Developer Console 上没有很好的记录。

Google Cloud SQL 2nd Gen 需要在您的代码中未提供的连接字符串中进行一些修改。

请看我这边修改后的原代码:

class MainPage(webapp2.RequestHandler):

def get(self):

self.response.headers['Content-Type'] = 'text/plain'

#db connection
if (os.getenv('SERVER_SOFTWARE') and
    os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
    db = MySQLdb.connect(unix_socket='/cloudsql/<project-id>:europe-west1<instance-name>, db = 'your-db', user= 'root', passwd='your-root-password')
else:
    db = MySQLdb.connect(host = '10.10.0.1', port=3306,
                                    db = 'your-db', user='root', passwd='root-password')

cursor = db.cursor()
cursor.execute('SELECT 1 + 1')

self.response.write('pong')

app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)

此致。