使用带有postgres的flask sqlalchemy更新状态将不会提交到数据库 [英] update state with flask sqlalchemy with postgres will not commit to database

查看:205
本文介绍了使用带有postgres的flask sqlalchemy更新状态将不会提交到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多文档,但看不到这些行有什么问题

I have read quite a bit of documentation and I can't see what is wrong with these lines

update_this = User.query.filter_by(email=email).first()
update_this.emailconfirmed = True
db.session.commit()

...但是当我部署布尔列 emailconfirmed时,永远不会更新为True。我已经通过打印语句确认了 update_this.emailconfirmed 在上面显示的代码的确切点上是False ...我似乎无法更新该值。有人知道我可以做哪些测试,应该检查哪些进口等等。

...and yet when I deploy the boolean column 'emailconfirmed' never is update to True. I have confirmed with print statements that update_this.emailconfirmed is False at the exact point in the code shown above... I just can't seem to update that value. Does anybody know what tests I can do, what imports I should check etc. etc.

现在这是我的主.py文件的顶部,上面的代码出现在这里

Right now this is the top of my main .py file where the above code appears

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文件

and this is my models.py file

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)

对我进行上述更新的任何帮助将不胜感激!

Any help on doing the update I mentioned above would be greatly appreciated!!

推荐答案


理想情况下,您希望在整个应用程序生命周期中维护一个会话。这样,就可以轻松地进行推理,并且避免将会话绑定到各个模型。

Ideally you want to maintain a single session throughout your application lifecycle. This way it makes it easy to reason about and you avoid binding sessions to individual models.

感谢@Ilja Everila

Thanks @Ilja Everila

main.py 中,而不是初始化 SQLAlchemy

In main.py instead of initializing SQLAlchemy you should write,

db.init_app(app)

为用户模型定义保存实例方法。

def save(self):
    """Saves model object instance
    """
    db.session.add(self)
    db.session.commit()

您可以调用此方法将实例另存为

You can call this method to save the instance as

update_this.save()

更新实体的另一种方法是在提交前获取特定的对象会话

from sqlachemy.orm import session
...
session = session.object_session(update_this)
session.commit()

这篇关于使用带有postgres的flask sqlalchemy更新状态将不会提交到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆