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
try/execeptblock is hiding an error. Try cast you net wider and see if there's a non-pymysql.MySQLErrorcoming through.if os.environ.get('GAE_ENV') == 'standard':and it should workconn=Noneto the first line ofopen_connection.