今天做一个简单的flask_sqlalchemy demo,最后在执行的时候遇到了KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'。。。真的是不知道怎么做了,我在数据库操作页model.py页,声明了这些东西,还是报这个错
#model.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = 'development key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost/test1'
#这两个值都设置了,,。。。
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), unique=True)
password = db.Column(db.String(32))\
def __init__(self, username, password):
self.username = username
self.password = password
def add(self):
try:
db.session.add(self)
db.session.commit()
return '注入数据库成功'
except Exception as e:
db.session.rollback()
return e
finally:
return 0
def isExisted(self):
tempuser = User.query.filter_by(username=self.username, password=self.password).first()
if tempuser is None:
return 0
else:
return 1
后来发现大佬写的文章
https://www.cnblogs.com/zhangchenglzhao/p/9774004.html
我仔细看了下,和我的问题相似。解决方法就是只生成一个app,使用的时候引入过来就好了
# app.py
from flask import Flask, render_template, request, redirect
# 用一般的方法查询注册
# from db import *
# 用对象的方法注册查询
from model import *
from wtforms import StringField, PasswordField, validators, Form
#就是因为这两句,在这个app.py中也生成了一个app。但是没有任何设置,所以导致除了一系列的问题...
#app = Flask(__name__)
#app.secret_key = 'development key'
class loginForm(Form):
username = StringField("username", [validators.DataRequired()])
password = PasswordField("password", [validators.DataRequired()])
@app.route('/register', methods=["POST", "GET"])
def register():
myForm = loginForm(request.form)
if request.method == "POST":
u = User(myForm.username.data, myForm.password.data)
u.add()
return "注册成功"
return render_template('index.html', form=myForm)
@app.route('/login', methods=["POST", "GET"])
def login():
myform = loginForm(request.form)
if request.method == "POST":
username = myform.username.data
password = myform.password.data
aaa = myform.validate()
u = User(username, password)
if u.isExisted() and myform.validate():
return redirect('http://www.baidu.com')
else:
message = 'login failed'
return render_template('index.html', message=message, form=myform)
return render_template('index.html', form=myform)
if __name__ == '__main__':
app.run(debug=True)
网友评论