无法使用 Google 函数中的 Python 脚本 运行 连接到 Google SQL 数据库
Can't connect to Google SQL Database with Python Script run in Google Functions
此 python 脚本的目的是从 google 分析中提取数据并将其添加到 google MySQL 数据库中。该脚本适用于我的本地计算机,但不适用于 google 函数:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import mysql.connector
from datetime import datetime
from datetime import timedelta
import os
from mysql.connector import errorcode
def main(data, context):
# MySQL
DB_NAME = 'GA_Data1'
cnx = mysql.connector.connect(user=user1, password=password1,
host=hostip, database=DB_NAME)
当我运行上面的代码时,我得到了这些错误:
- error messages
我想这可能是因为 google 的机器的 IP 地址没有列入我的 SQL 数据库的白名单。我尝试添加一个带有外部 IP 地址的云 NAT,这样我就可以将它列入白名单。那没有用。这是 link 到 an article that helps connect to a SQL database with python。我应该用本文中的代码替换我的一些代码吗?
我拒绝更改任何内容,因为它在我的计算机上运行良好。因此,问题出在 google 机器上的脚本 运行ning 的某个地方。
您需要添加一个 VPC 连接器,以便它可以私下直接连接到 SQL 服务器。
见https://cloud.google.com/sql/docs/mysql/connect-functions
它在出口侧的“网络”下。您必须在 Google 云项目中启用一些功能,但它应该会引导您完成它。
我建议在 SQL 数据库端启用“私有 IP”。
然后在您的函数中使用该私有 IP 进行连接,并选中该框以仅在 Cloudfunction 上路由私有 IP(以防您也在其中做其他一些事情):
此 python 脚本的目的是从 google 分析中提取数据并将其添加到 google MySQL 数据库中。该脚本适用于我的本地计算机,但不适用于 google 函数:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import mysql.connector
from datetime import datetime
from datetime import timedelta
import os
from mysql.connector import errorcode
def main(data, context):
# MySQL
DB_NAME = 'GA_Data1'
cnx = mysql.connector.connect(user=user1, password=password1,
host=hostip, database=DB_NAME)
当我运行上面的代码时,我得到了这些错误:
- error messages
我想这可能是因为 google 的机器的 IP 地址没有列入我的 SQL 数据库的白名单。我尝试添加一个带有外部 IP 地址的云 NAT,这样我就可以将它列入白名单。那没有用。这是 link 到 an article that helps connect to a SQL database with python。我应该用本文中的代码替换我的一些代码吗?
我拒绝更改任何内容,因为它在我的计算机上运行良好。因此,问题出在 google 机器上的脚本 运行ning 的某个地方。
您需要添加一个 VPC 连接器,以便它可以私下直接连接到 SQL 服务器。
见https://cloud.google.com/sql/docs/mysql/connect-functions
它在出口侧的“网络”下。您必须在 Google 云项目中启用一些功能,但它应该会引导您完成它。
我建议在 SQL 数据库端启用“私有 IP”。
然后在您的函数中使用该私有 IP 进行连接,并选中该框以仅在 Cloudfunction 上路由私有 IP(以防您也在其中做其他一些事情):