【问题标题】:Google Cloud SQL - Python Flask connection issueGoogle Cloud SQL - Python Flask 连接问题
【发布时间】:2021-01-09 04:26:12
【问题描述】:

我正在尝试按照本教程使 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

【问题讨论】:

  • 我的第一个想法是你的try/execept 块隐藏了一个错误。试着把你的网撒得更广,看看是否有非pymysql.MySQLError 进来。
  • 谢谢@PGHE。错误似乎出现在“return conn”而不是 pymysql。我不知道为什么它没有被分配,特别是因为我没有改变教程中的任何东西。
  • 我认为你应该删除if os.environ.get('GAE_ENV') == 'standard': ,它应该可以工作
  • 要调试,只需在open_connection的第一行添加conn=None即可。

标签: python google-app-engine flask global google-cloud-sql


【解决方案1】:

根据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"

我检查了教程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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 2021-12-25
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    相关资源
    最近更新 更多