Google Cloud SQL-Python Flask连接问题



我正试图让Flask应用程序与Google Cloud SQL一起使用本教程:

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

除了MySQL连接之外,一切都很顺利,它触发了这个UnboundLocalError: local variable 'conn' referenced before assignment错误,这个错误似乎更多地与python有关,而不是与教程中的框架有关。有什么想法吗?

以下是导致问题的代码:

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

错误消息:

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

根据官方文件:

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"

我检查了教程app.yaml文件,但没有设置变量GAE_ENV

#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

因此,我认为您的if condition是错误的,并且在分配之前参考了con

相关内容

  • 没有找到相关文章

最新更新