簡體   English   中英

如何修復“”AttributeError: 'NoneType' 對象沒有屬性 'app'

[英]How to fix ""AttributeError: 'NoneType' object has no attribute 'app'

我是 Web 框架的新手,我正在嘗試做一個簡單的項目。 我想在 html 頁面上顯示 MySQL 數據,但是我一直收到這個 AttributeError: 'NoneType' object has no attribute 'app'。

我查看了其他解決方案,但似乎無法弄清楚我做錯了什么。 任何幫助,將不勝感激。 我確實運行了這段代碼:

測試文件

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

print(hello_world())

這運行良好。

蟒蛇代碼

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測試剛好工作,因為該視圖返回一個簡單的字符串。

但是doQuery視圖返回一個模板渲染,它更復雜,並且需要一個實際的 web 請求上下文,當您直接調用函數時缺少該上下文。

嘗試在 Google 的 AppEngine 上運行 Python 代碼時遇到了類似的錯誤。 解決方案是使用app.config.update()來指定服務器。 我使用SERVER_NAME來做到這一點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM