回答
:
beta_settings:
cloud_sql_instances: [INSTANCE_CONNECTION_NAME]
で、私の質問への短い答えはノー」であり、あなたはSQLAlchemyのを使用する必要はありません。」
詳細情報
ホスト名、サンプルアプリケーションに記載されているように、/cloudsql/[INSTANCE_CONNECTION_NAME]
であるあなたは、コマンドラインから[INSTANCE_CONNECTION_NAME]
を取得することができます:「のgcloud SQLリスト」ご自分のインスタンス名を伝え、その後、「のgcloud SQLは[instance name]
を記述する」あなたに1つのインスタンスについて多くを伝えます(そのconnectionName
を含む)、その値は[INSTANCE_CONNECTION_NAME]
です。
私のコードでは、cloud_sql_proxy
が実行中であるかどうかに応じて、ローカルでテストするときにdbのローカルコピーまたはクラウドdbに接続します。デプロイされると、アプリケーションはクラウドdbにアクセスします。これはすべてこの関数にカプセル化されています:
def pg_connect(str):
""" Connect to local db, use proxy, or connect directly.
If USE_LOCAL_DB is set, connect to that db locally (default user, etc.)
Otherwise, use /cloudsql/... on port 5432, unless port 5431 is bound,
in which case the proxy server is running, and the host is localhost
on port 5431. (The proxy port number is specified when starting
cloud_sql_proxy.)
"""
dbname = os.environ.get('USE_LOCAL_DB')
if dbname != None:
return psycopg2.connect('dbname={}'.format(dbname))
# Extract the dbname from the connection string and set up for deployed GAE
# access.
dbname = re.search('dbname=(\w*)', str).group(1)
port = 5432
host = '/cloudsql/...'
user = '...'
password = '...'
# if port 5431 is bound, the proxy is running, and the connection string
# refers to localhost on that port
s = socket.socket()
try:
c = s.bind(('localhost', 5431))
except:
# Unable to bind: proxy must be running
host = 'localhost'
port = 5431
s.close()
conn_str = 'dbname={} host={} port={} user={} password={}'.format(
dbname,
host,
port,
user,
password)
return psycopg2.connect(conn_str)