2017-08-30 21 views
0

postgresに接続するためのサンプルコードでは、SQLAchemyを使用しています。これは必須か、従来のpsycopg2接続文字列でホストを指定する方法ですか? ( "dbname = ... host = ... port = ... etc")、SQLAlchemyを避けます。GAEフレキシブル環境postgres接続文字列?

私はdbにアクセスするには、cloud_sql_proxyを使用してください。私は配備されたアプリからそれにアクセスできません。私は何を失敗したことは、私のapp.yamlファイルに必要な設定を含めることでした

答えて

0

回答

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) 
関連する問題