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
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
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.