我是python的新手,我通过尝试将连接变量分配给不同的.py文件中的函数而得到上述错误我试图将连接设置为无,但没有解决我的问题视图.pyfrom datetime import datetimefrom flask import render_template, request, redirect, url_for, flashfrom FlaskWebProject1 import appimport jsonimport mysql.connectorfrom mysql.connector import Errorimport 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 = Nonedef 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' ]
1 回答
MM们
TA贡献1886条经验 获得超2个赞
错误显示
NameError: name 'db' is not defined`
所以这是你的主要问题和其他问题的根源。
你有
import FlaskWebProject1.db
FlaskWebProject1.
所以你需要
connection = FlaskWebProject1.db.get_connection()
或者你应该导入
from FlaskWebProject1 import db
添加回答
举报
0/150
提交
取消