我尝试使用蓝图重新构建我的应用程序,一旦完成,我收到错误:“NameError: name 'db' is not defined” 我不明白为什么会出现错误
这是我的init .py 文件:app 和 db 的初始化位置
import os
from flask import Flask
def create_app():
app = Flask(__name__)
from svc.base.routes import base
from svc.admin.routes import admin
from svc.auth.routes import auth
from flaskext.mysql import MySQL
db = MySQL(app)
db.init_app(app)
app.config['SECRET_KEY'] = 'MySecretKey'
app.config['MYSQL_DATABSE_HOST'] = os.environ.get('DB_HOST')
app.config['MYSQL_DATABASE_PORT'] = os.environ.get('DB_PORT')
app.config['MYSQL_DATABASE_USER'] = os.environ.get('DB_USER')
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ.get('DB_PASSWORD')
app.config['MYSQL_DATABASE_DB'] = os.environ.get('DB_DATABASE')
app.register_blueprint(admin)
app.register_blueprint(base)
app.register_blueprint(auth)
return app
我的 routes.py 文件在重组后发生错误。
from flask import Blueprint, render_template
from .forms import LoginForm
from svc import create_app
auth = Blueprint('auth', __name__, template_folder='templates')
@auth.route('/login', methods=['POST', 'GET'])
def login():
form=LoginForm()
if form.validate_on_submit():
email = form.email.data
password = (form.password.data).encode('utf-8')
cur = db.get_db().cursor()
cur.execute("SELECT * FROM `user` WHERE `user_email` = %s",(form.email.data))
user = cur.fetchone()
cur.close()
if user:
username = user[1]
role = user[5]
session_id = user[0]
if bcrypt.hashpw(password, (user[4].encode('utf-8'))) == (user[4].encode('utf-8')):
session['loggedin'] = True
session['id'] = session_id
session['user'] = username
session['role'] = role
flash(f'Login Successful for {user[1]} {user[2]}', category='success')
return redirect(url_for('account'))
else:
flash(f'Login Unsuccessful - Incorrect Password', category='danger')
else:
flash(f'Login Unsuccessful - Incorrect Email', category='danger')
return render_template('login.html', title='Login',form=form)