我已经阅读了相当多的文档,我看不出这些行有什么问题
update_this = User.query.filter_by(email=email).first()
update_this.emailconfirmed = True
db.session.commit()
...然而当我部署布尔列时,电子邮件确认了'永远不会更新为True。我已经使用打印语句确认update_this.emailconfirmed
在上面显示的代码中的确切位置为False ...我似乎无法更新该值。有谁知道我可以做什么测试,我应该检查哪些进口等等。
现在这是我的主.py文件的顶部,其中出现上述代码
from flask import Flask, render_template, request, session, redirect, url_for, make_response
# the following line imports from models.py
from models import db, User
# the following line imports SignupForm from forms.py
from forms import SignupForm, LoginForm
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer
# Production (causes Heroku to redirect to SSL)
from flask_sslify import SSLify
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
sslify = SSLify(app)
sslify = SSLify(app, subdomains=True)
app.config.from_pyfile('config_file.cfg')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)
mail = Mail(app)
ts = URLSafeTimedSerializer(app.config['SECRET_KEY'], salt=app.config['SALT'])
这是我的models.py文件
from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(100))
lastname = db.Column(db.String(100))
role = db.Column(db.String(20))
roleapproved = db.Column(db.Boolean)
school = db.Column(db.String(100))
email = db.Column(db.String(120), unique=True)
emailconfirmed = db.Column(db.Boolean)
pwdhash = db.Column(db.String(100))
def __init__(self, firstname, lastname, role, school, email, password):
self.firstname = firstname.title()
self.lastname = lastname.title()
self.role = role.lower()
if role.lower() == 'student':
self.roleapproved = True
if role.lower() == 'teacher':
self.roleapproved = False
self.school = school.title()
self.email = email.lower()
self.set_password(password)
self.emailconfirmed = False
def set_password(self, password):
self.pwdhash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
def __repr__(self):
return '<User {0}>'.format(self.email)
我非常感谢上面提到的有关更新的任何帮助!!
答案 0 :(得分:0)
理想情况下,您希望在整个应用程序生命周期中维护单个会话。通过这种方式,可以轻松推理并避免将会话绑定到单个模型。
谢谢@Ilja Everila
在main.py
而不是初始化SQLAlchemy
你应该写,
db.init_app(app)
为您的用户模型定义 save
实例方法。
def save(self):
"""Saves model object instance
"""
db.session.add(self)
db.session.commit()
您可以调用此方法将实例另存为
update_this.save()
更新实体的另一种方法是在提交之前获取特定的对象会话
from sqlachemy.orm import session
...
session = session.object_session(update_this)
session.commit()