2017-08-30 47 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)