簡體   English   中英

無法使用PyMySQL連接到Cloud SQL

[英]Can't connect to Cloud SQL using PyMySQL

我正在嘗試從運行在Google App Engine之上的Python應用程序(使用PyMySQL 0.7.9)連接到Cloud SQL。

我的連接字符串看起來像這樣(憑證當然是假的):

pymysql.connect(unix_socket='/cloudsql/gae_project_name:cloudsql_instance_name', 
                user='user', password='', db='database_name')

我收到的錯誤消息是:

OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 97] Address family not supported by protocol)")

這就像PyMySQL沒有意識到我正在嘗試通過Unix套接字連接並嘗試使用host參數的默認值(我認為是localhost

我能夠使用相同的連接字符串連接MySQLdb。

為什么不使用MySQLdb呢?

我在使用PyMySQL部署Flask應用程序時遇到了同樣的問題,我嘗試了很多修復但沒有成功。 我的解決方法是使用MySQLDb而不是aha ..!

顯然,Google App Engine標准環境目前不支持PyMySQL,該環境僅運行Python 2.7(截至2018年6月)。 這是來自GCP python項目的維護者:

我可以確認python27運行時不支持pymysql。 但是,對於大多數用例,可以在生產中使用pymysql和mysqldb,使用try:/除了ImportError:有條件地導入一個或另一個。 由於它們共享相同的接口,因此您可以使用import來使兩個不同的庫共享相同的名稱,以便在代碼中使用。

有關詳細信息,請參閱此Github線程

我使用Python3 Flex App Engine和PyMySQL進行連接。

這是我的app.yaml的樣子:

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT api:app --timeout 180

runtime_config:
  python_version: 3

env_variables:
  SQLALCHEMY_DATABASE_URI: >-
    mysql+pymysql://user:password@/database?unix_socket=/cloudsql/project-name:us-central1:instance-name

beta_settings:
  cloud_sql_instances: us-central1:instance-name

# This sample incurs costs to run on the App Engine flexible environment. 
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

確保在env_variables和beta_settings中替換用戶,密碼,數據庫和實例連接。

這是我的python:

import pymysql.cursors
import pymysql
connection = pymysql.connect(unix_socket='/cloudsql/project-name:us-central1:instance-name',
        user='user',
        password='password',
        db='database',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM