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

时间:2016-09-05 10:42:02

标签: python google-app-engine google-cloud-sql

尝试从App Engine连接到Google Cloud SQL。获取错误500并且日志显示:"访问被拒绝用户&root;' @x; cloudqlproxy~' (使用密码:否)")。 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,他们在同一个项目上!有没有办法检查数据库的权限是什么?

2 个答案:

答案 0 :(得分:1)

好的,事实证明有一些错误信息正在发生。添加密码参数解决了我的问题。但出于某种原因,在Google文档中没有提到这一点,而且StackOverflow上的很多帖子实际上都直接告诉您相反的情况,如果从AppEngine登录时传递密码,则说明Cloud SQL会抛出错误。也许最近的一些更新是导致这种情况的原因,但在我的情况下,传递密码解决了这个问题。希望有所帮助!

答案 1 :(得分:0)

我想说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)

问候。

相关问题