以下是一个示例,展示了如何在本地和通过App Engine Flex连接到Google Cloud SQL(PostgreSQL):
首先,确保您已经在Google Cloud上创建了一个Cloud SQL(PostgreSQL)实例。您可以按照官方文档的说明进行操作。
在本地连接到Cloud SQL(PostgreSQL):
import psycopg2
# 连接到Cloud SQL实例
connection = psycopg2.connect(
host='YOUR_INSTANCE_CONNECTION_NAME',
user='YOUR_DB_USERNAME',
password='YOUR_DB_PASSWORD',
dbname='YOUR_DB_NAME',
sslmode='require'
)
# 执行SQL查询
cursor = connection.cursor()
cursor.execute('SELECT * FROM your_table')
results = cursor.fetchall()
for row in results:
print(row)
# 关闭连接
cursor.close()
connection.close()
请将 YOUR_INSTANCE_CONNECTION_NAME
、YOUR_DB_USERNAME
、YOUR_DB_PASSWORD
和YOUR_DB_NAME
替换为您的实际信息。
首先,在您的App Engine Flex的app.yaml
文件中添加以下内容:
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app
runtime_config:
# 连接到Cloud SQL实例
connection_name: YOUR_INSTANCE_CONNECTION_NAME
manual_scaling:
instances: 1
请将 YOUR_INSTANCE_CONNECTION_NAME
替换为您的实际信息。
然后,在您的主应用程序文件(例如main.py
)中添加以下内容:
import os
import psycopg2
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
# 连接到Cloud SQL实例
connection = psycopg2.connect(
host='/cloudsql/' + os.environ['INSTANCE_CONNECTION_NAME'],
user=os.environ['DB_USERNAME'],
password=os.environ['DB_PASSWORD'],
dbname=os.environ['DB_NAME'],
sslmode='require'
)
# 执行SQL查询
cursor = connection.cursor()
cursor.execute('SELECT * FROM your_table')
results = cursor.fetchall()
response = ''
for row in results:
response += str(row) + '\n'
# 关闭连接
cursor.close()
connection.close()
return response
if __name__ == '__main__':
app.run()
请将 YOUR_INSTANCE_CONNECTION_NAME
、DB_USERNAME
、DB_PASSWORD
和DB_NAME
替换为您的实际信息。
以上代码示例演示了如何在本地和通过App Engine Flex连接到Google Cloud SQL(PostgreSQL)。请根据您的实际情况进行修改和调整。