GAE灵活环境postgres连接字符串?

时间:2017-08-30 22:17:26

标签: python postgresql google-app-engine

连接到postgres的示例代码使用SQLAchemy。这是必需的,还是有办法在传统的psycopg2连接字符串中指定主机? (“dbname = ... host = ... port = ... etc”),避免使用SQLAlchemy。

我可以使用cloud_sql_proxy访问数据库就好了。我无法从已部署的应用程序中获取它。

1 个答案:

答案 0 :(得分:0)

<强>答案

我未能做的是在app.yaml文件中包含必要的设置:

beta_settings:
  cloud_sql_instances: [INSTANCE_CONNECTION_NAME]

也就是说,对我的问题的简短回答是,“不,你不必使用SQLAlchemy。”

更多信息

示例应用中记录的主机名为/cloudsql/[INSTANCE_CONNECTION_NAME]

您可以从命令行获取[INSTANCE_CONNECTION_NAME]:&#34; gcloud sql list&#34;告诉你你的实例名称,然后&#34; gcloud sql describe [instance name]&#34;告诉您很多关于一个实例的信息,包括connectionName,其值为[INSTANCE_CONNECTION_NAME]

在我的代码中,我在本地测试时连接到db的本地副本或cloud db,具体取决于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)