我正在構建一個簡單的使用現有MySQL數據庫的網絡應用程序。這是我第一次使用Flask,我一直在努力理解過去幾個小時我做錯了什麼。燒瓶+ MySQL的奇怪行爲
我簡單的項目結構:
/root
/app
__init__.py
db.py
forms.py
views.py
/templates
base.html
index.html
login.html
config.py
run.py
我想查詢我的MySQL數據庫,並從查詢結果填寫模板。
我db.py:
from app import app
from flaskext.mysql import MySQL
class DB(object):
mysql = MySQL()
def __init__(self):
app.config['MYSQL_DATABASE_USER'] = 'loguser'
app.config['MYSQL_DATABASE_PASSWORD'] = 'asdzxc'
app.config['MYSQL_DATABASE_DB'] = 'log'
app.config['MYSQL_DATABASE_HOST'] = '127.0.0.1'
app.config['MYSQL_DATABASE_PORT'] = 33006
self.mysql.init_app(app)
def query_db(self):
cursor = self.mysql.connect().cursor()
cursor.execute("SELECT name from users limit 1")
data = cursor.fetchone()
if data is None:
return "No results from query"
else:
return data
而在我的views.py我有以下幾點:
from flask import render_template, flash, redirect
from app import app
from .forms import LoginForm
from .db import DB
@app.route('/')
@app.route('/index')
def index():
db = DB()
user = db.query_db()
print(user) (it prints it here so the db connection works)
posts = [ # fake array of posts
{
'author': {'nickname': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'nickname': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template("index.html",
title='Home',
user=user,
posts=posts)
我得到 「Asse田」 當我嘗試指派 「用戶」 用戶從模板:
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
我相信我違反了框架的一個主要原則。將數據傳遞給模板的正確方法是什麼?