我是网络框架的新手,我正在尝试做一个简单的项目。我想在 html 页面上显示 MySQL 数据,但是我不断收到此 AttributeError: 'NoneType' 对象没有属性 'app'。
我看过其他解决方案,但我似乎无法弄清楚我做错了什么。任何帮助,将不胜感激。我确实运行了这段代码:
TEST.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
print(hello_world())
并且运行良好。
Python代码
import mysql.connector
from flask import Flask, render_template
app = Flask(__name__)
hostname = ''
username = ''
password = ''
database = ''
#run query on a database
@app.route('/')
def doQuery(conn):
cur = conn.cursor()
query = "SELECT * FROM maxes"
cur.execute(query)
data = cur.fetchall()
return render_template("weightlifting.html", data=data)
print("Using mysql.connector")
myConnection = mysql.connector.connect(host=hostname, user=username, password=password, db=database)
doQuery(myConnection)
myConnection.close()
这是我收到的错误:
Using mysql.connector
Traceback (most recent call last):
File "database.py", line 24, in <module>
doQuery(myConnection)
File "database.py", line 20, in doQuery
return render_template("weightlifting.html", data=data)
File "C:\Users\kbb_n\Anaconda3_2\lib\site-packages\flask\templating.py", line 133, in render_template
ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'
最佳答案
一般来说,您实际上不应该直接调用路由函数。
您的 hello_world
测试恰好有效,因为该 View 返回一个简单的字符串。
但是 doQuery
View 返回一个模板渲染,这更加复杂并且需要实际的 Web 请求上下文,而当您直接调用该函数时会缺少该上下文。
关于python - 如何修复 ""属性错误: 'NoneType' object has no attribute 'app' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750527/