获取“UnboundLocalError:分配前引用的局部变量'连接'”

我是python的新手,我通过尝试将连接变量分配给不同的.py文件中的函数而得到上述错误


我试图将连接设置为无,但没有解决我的问题


视图.py

from datetime import datetime

from flask import render_template, request, redirect, url_for, flash

from FlaskWebProject1 import app


import json

import mysql.connector

from mysql.connector import Error

import FlaskWebProject1.db 




@app.route('/')

@app.route('/users')

def users():


  try: 

    lstUsers = ''


    #connect to DB

    connection = db.get_connection()


    if connection.is_connected():

        #db_Info = connection.get_server_info()

        #print("Connected to MySQL Server version ", db_Info)

        cursor = connection.cursor(dictionary=True)

        cursor.execute("select * from users;")

        record = cursor.fetchall()

        lstUsers = record       

        #print("Your connected to database: ", record)

  except Error as e:

         print("Error while connecting to MySQL", e) 

  finally:

        if (connection.is_connected()):

            cursor.close()

            connection.close()

            print("MySQL connection is closed")


  return render_template('users.html',

    title = 'Users Page', 

    users = lstUsers)

数据库.py

_connection = None


def get_connection():

    global _connection

    if not _connection:

        _connection = mysql.connector.connect(user="bla@bla", 

                       password='bla', 

                       host="mysql.database.azure.com", 

                       port=3306, 

                       database='testdb')

        return _connection


# List of stuff accessible to importers of this module. Just in case

__all__ = [ 'getConnection' ]


墨色风雨
浏览 95回答 1
1回答

MM们

错误显示NameError: name 'db' is not defined`所以这是你的主要问题和其他问题的根源。你有import FlaskWebProject1.dbFlaskWebProject1.所以你需要connection = FlaskWebProject1.db.get_connection()或者你应该导入from FlaskWebProject1 import db
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python