【问题标题】:How to fix ""AttributeError: 'NoneType' object has no attribute 'app'如何修复“”AttributeError:“NoneType”对象没有属性“app”
【发布时间】:2019-09-02 01:12:50
【问题描述】:

我是 web 框架的新手,我正在尝试做一个简单的项目。我想在 html 页面上显示 MySQL 数据但是我不断收到这个 AttributeError: 'NoneType' object has no attribute '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'

【问题讨论】:

标签: python mysql flask


【解决方案1】:

一般来说,你不应该直接调用路由函数。

您的 hello_world 测试恰好工作,因为该视图返回一个简单的字符串。

但是doQueryview返回的是模板渲染,比较复杂,需要一个实际的web请求上下文,直接调用函数就没有了。

【讨论】:

    【解决方案2】:

    尝试在 Google 的 AppEngine 上运行 Python 代码时,我遇到了类似的错误。解决方案是使用app.config.update() 指定服务器。我使用SERVER_NAME 来做到这一点:

    app.config.update(
        SERVER_NAME = "127.0.0.1:8080"
    )
    

    【讨论】:

      猜你喜欢
      • 2013-06-16
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多