【问题标题】:Connecting to MySQL DB from App Engine从 App Engine 连接到 MySQL 数据库
【发布时间】:2017-05-11 10:31:26
【问题描述】:

我是在 App Engine 中使用 MySQL 数据库的新手,我希望有人可以帮助我解决我遇到的问题。我有一个函数connect_to_cloudsql(),它与本地或云数据库建立连接,这是我从 Google Academy 教程中获得的。代码如下:

# These environment variables are configured in app.yaml. CLOUDSQL_CONNECTION_NAME = os.environ.get(<something here>) CLOUDSQL_USER = os.environ.get(<something here>) CLOUDSQL_PASSWORD = os.environ.get(<something here>)

def connect_to_cloudsql():
    # When deployed to App Engine, the 'SERVER_SOFTWARE' environment variable
    # will be set to 'Google App Engine/version'.
    if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
        # Connect using the unix socket located at
        # /cloudsql/cloudsql-connection-name.
        cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)

        db = MySQLdb.connect(
            unix_socket=cloudsql_unix_socket,
            user=CLOUDSQL_USER,
            passwd=CLOUDSQL_PASSWORD)

    # If the unix socket is unavailable, then try to connect using TCP. This
    # will work if you're running a local MySQL server or using the Cloud SQL
    # proxy, for example:
    # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306

    else:
        db = MySQLdb.connect(host='localhost', port=3310, user='root', passwd='something here', db='DB1')

    return db

然后我在我的课程中使用connect_to_cloudsql() 连接到数据库。该代码在本地运行良好,但是当我部署并尝试使用它时,出现以下错误:

File "/base/data/home/apps/s~reliance-group/1.401176020169136394/sql/tests.py", line 70, in get
con = connect_to_cloudsql()
File "/base/data/home/apps/s~reliance-group/1.401176020169136394/sql/tests.py", line 45, in connect_to_cloudsql
'/cloudsql', CLOUDSQL_CONNECTION_NAME)
File "/base/data/home/runtimes/python27_experiment/python27_dist/lib/python2.7/posixpath.py", line 68, in join
if b.startswith('/'):
AttributeError: 'NoneType' object has no attribute 'startswith'

【问题讨论】:

    标签: python mysql google-app-engine google-cloud-sql


    【解决方案1】:

    这里的错误是

    CLOUDSQL_CONNECTION_NAMENone。可能是你没有为此设置环境变量。

    【讨论】:

    • 嗨 L_S。我确实在 app.yaml 中设置了环境变量。我设置了变量CLOUDSQL_CONNECTION_NAMECLOUDSQL_USERCLOUDSQL_PASSWORD。我还有什么遗漏的吗?
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2020-02-03
    • 2021-01-02
    相关资源
    最近更新 更多