简体   繁体   中英

Connecting to MySQL DB from App Engine

I am new to using MySQL databases with App Engine and I was hoping someone could help me with a problem I am having. I have a function connect_to_cloudsql() that establishes a connection with the local or cloud database, which I got from the Google Academy tutorial. The code is below:

# 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

I then use the connect_to_cloudsql() in my classes to connect to the database. The code works fine locally, but when I deploy and try to use it I get the following error:

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'

Here the error is

CLOUDSQL_CONNECTION_NAME is None . May be you didnt set up environment variable for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM