2017-08-30 46 views
0

用於連接到postgres的示例代碼使用SQLAchemy。這是必需的,還是有辦法指定傳統的psycopg2連接字符串中的主機? (「dbname = ... host = ... port = ... etc」),避免SQLAlchemy。GAE靈活環境postgres連接字符串?

我可以使用cloud_sql_proxy就好了訪問數據庫。我無法從部署的應用程序中獲取它。

回答

0

回答

我未能做的是,包括必要的設置,在我的app.yaml文件:

beta_settings: 
    cloud_sql_instances: [INSTANCE_CONNECTION_NAME] 

也就是說,簡短的回答我的問題是,「不你不必使用SQLAlchemy。」

更多信息

的主機名,如示例應用程序文件,是/cloudsql/[INSTANCE_CONNECTION_NAME]

你可以在命令行中得到[INSTANCE_CONNECTION_NAME]:「gcloud SQL列表」告訴你,你的實例名稱,然後選擇「gcloud sql中描述[instance name]」告訴你許多關於一個實例,包括其connectionName,其價值是你的[INSTANCE_CONNECTION_NAME]

在我的代碼在本地測試時,取決於是否cloud_sql_proxy正在運行或無法連接到數據庫的一個本地副本或雲分貝。部署時,應用程序訪問雲數據庫。這一切都封裝在這個函數:

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)