我是这个谷歌应用程序引擎的新手。我写了一个小的Python代码,旨在连接谷歌云中的数据库。不幸的是我收到了这个错误。
Traceback (most recent call last):
File "/home/revanth/Projects/workspace/project2/connect.py", line 28, in <module>
main()
File "/home/revanth/Projects/workspace/project2/connect.py", line 19, in main
user='revanth'
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'revanth'@'76.183.80.171' (using password: NO)")
这是我的Python代码
import googleapiclient
import MySQLdb
import os
#from google.storage.speckle.python.api import rdbms_googleapi
def main():
env = os.getenv('SERVER_SOFTWARE')
if (env and env.startswith('Google App Engine/')):
# Connecting from App Engine
db = MySQLdb.connect(
unix_socket='/cloudsql/citric-cistern-97118:geoeq',
user='revanth')
else:
# Connecting from an external network.
# Make sure your network is whitelisted
db = MySQLdb.connect(
host='173.194.232.179',
port=3306,
user='revanth'
)
cursor = db.cursor()
cursor.execute('select * from Whether')
rows = cursor.fetchall()
print rows
if __name__ == '__main__':
main()
请帮帮我。
要授予对 App Engine 应用程序的访问权限:
注意:为了保证低延迟,通过在创建实例时选择首选位置或配置现有实例,可以使 Google Cloud SQL 实例尽可能靠近指定的 App Engine 应用程序。这仅适用于在美国和欧盟位置创建的实例。 单击“保存”应用您的更改。
我找到了解决办法。我只需要添加 0.0.0.0/0 即可允许所有外部 IP 地址连接它。
这是链接:https://cloud.google.com/sql/docs/access-control
我需要在选项中指定密码。
我认为您的
import MySQLdb
存在兼容性问题。
我在谷歌云运行中遇到了同样的问题。我的代码在本地计算机上运行良好,但在云运行中运行时出现错误“mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '34.105.87.213:3306' (110)”
我换成sqlalchemy lib,问题就消失了。
旧库:
import os
import mysql.connector
HOMAPP_NEWS_URL = "xxxxxxxx"
def write_to_db(contents):
# MySQL数据库连接配置
config = {
'host': os.environ.get("HOST"),
'port': os.environ.get("PORT"),
'database': os.environ.get("DB_NAME"),
'user': os.environ.get("DB_USER"),
'password': os.environ.get("DB_PASS"),
'raise_on_warnings': True
}
# 连接到MySQL数据库
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
for content in contents:
# 遍历contents数组,并将数据写入MySQL数据库
for news in content:
# 准备SQL插入语句
insert_query = "INSERT INTO t_news (source, title, content, url, pics, type, status, update_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
insert_values = (news.source, news.title, news.content, news.url, HOMAPP_NEWS_URL, news.type, news.status, news.update)
# 执行SQL插入语句
cursor.execute(insert_query, insert_values)
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
print("Write db completed")
新库:
import os
import sqlalchemy
HOMAPP_NEWS_URL = "XXXXXXXXXX"
def write_to_db(contents):
# MySQL数据库连接配置
db_user = os.environ["DB_USER"] # e.g. 'my-database-user'
db_pass = os.environ["DB_PASS"] # e.g. 'my-database-password'
db_name = os.environ["DB_NAME"] # e.g. 'my-database'
unix_socket_path = os.environ["INSTANCE_CONNECTION_NAME"] # e.g. '/cloudsql/project:region:instance'
pool = sqlalchemy.create_engine(
# Equivalent URL: mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=<socket_path>/<cloud_sql_instance_name>
sqlalchemy.engine.url.URL.create(
drivername="mysql+pymysql",
username=db_user,
password=db_pass,
database=db_name,
query={"unix_socket": unix_socket_path},
),
)
# 连接到MySQL数据库
with pool.connect() as conn:
stmt = sqlalchemy.text(
f"INSERT INTO t_news (source, title, content, url, pics, type, status, update_date)"
" VALUES (:source, :title, :content, :url, :pics, 'Repost', 'Publish', :update_date)"
)
# 遍历contents数组,并将数据写入MySQL数据库
for content in contents:
for news in content:
# 执行SQL语句
conn.execute(stmt, {
'source': news.source,
'title': news.title,
'content': news.content,
'url': news.url,
'pics': HOMAPP_NEWS_URL,
'update_date': news.update
})
conn.commit()
# 关闭数据库连接
conn.close()
print("Write db completed")