0

I'm trying to make a Flask app work with Google Cloud SQL following this tutorial:

https://www.smashingmagazine.com/2020/08/api-flask-google-cloudsql-app-engine/

Everything is going well except for the MySQL connection, which triggers this UnboundLocalError: local variable 'conn' referenced before assignment error that seems more to do with python than the frameworks in the tutorial. Any thoughts?

Here's the code that is causing the problem:

def open_connection():
    unix_socket = '/cloudsql/{}'.format(db_connection_name)
    try:
        if os.environ.get('GAE_ENV') == 'standard':
            conn = pymysql.connect(user=db_user, password=db_password,
                                unix_socket=unix_socket, db=db_name,
                                cursorclass=pymysql.cursors.DictCursor
                                )
    except pymysql.MySQLError as e:
        print(e)

    return conn

def get_songs():
    conn = open_connection()
    with conn.cursor() as cursor:
        result = cursor.execute('SELECT * FROM songs;')
        songs = cursor.fetchall()
        if result > 0:
            got_songs = jsonify(songs)
        else:
            got_songs = 'No Songs in DB'
    conn.close()
    return got_songs

Error message:

    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/timpeterson/python/flask-app/api/main.py", line 16, in songs
    return get_songs()
  File "/Users/timpeterson/python/flask-app/api/db.py", line 26, in get_songs
    conn = open_connection()
  File "/Users/timpeterson/python/flask-app/api/db.py", line 23, in open_connection
    return conn
UnboundLocalError: local variable 'conn' referenced before assignment
4
  • My first thought is your try/execept block is hiding an error. Try cast you net wider and see if there's a non-pymysql.MySQLError coming through. Commented Sep 23, 2020 at 3:27
  • Thanks @PGHE. The error seems at the ‘return conn’ rather than at pymysql. I can’t figure out why it wasn’t assigned especially because I didn’t change anything from the tutorial. Commented Sep 23, 2020 at 3:48
  • I think you should remove if os.environ.get('GAE_ENV') == 'standard': and it should work Commented Sep 23, 2020 at 8:34
  • To debug, just add conn=None to the first line of open_connection. Commented Sep 23, 2020 at 13:08

1 Answer 1

2

According to the official documentation:

Optional. You can define environment variables in your app.yaml file to make them available to your app.

Environment variables that are prefixed with GAE are reserved for system use and not allowed in the app.yaml file.

These variables will be available in the os.environ dictionary:
env_variables:
  DJANGO_SETTINGS_MODULE: "myapp.settings"

I checked the tutorial app.yaml file and the variable GAE_ENV was not set.

#app.yaml
runtime: python37

env_variables:
  CLOUD_SQL_USERNAME: YOUR-DB-USERNAME
  CLOUD_SQL_PASSWORD: YOUR-DB-PASSWORD
  CLOUD_SQL_DATABASE_NAME: YOUR-DB-NAME
  CLOUD_SQL_CONNECTION_NAME: YOUR-CONN-NAME

Therefore I believe your if condition is false and the con is referenced before assignment

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.