简体   繁体   English

Flask:从db检索数据并存储它的会话

[英]Flask : retrieve data from db and store it session

I have db.model like : 我有db.model喜欢:

class UserProfile(db.Model):
  __tablename__ = 'UserProfile'
  nickname = db.Column(db.String(40), primary_key=True)
  wm = db.Column(db.Boolean)

def __init__(self,name):
    self.nickname = name
    self.wm  = 1

def __repr__(self):
    return '<UserProfile {nickname}>'.format(username=self.nickname)

And during user login - I'm trying to retrive the record from db and store its value in a session variable - 在用户登录期间 - 我正在尝试从db中检索记录并将其值存储在会话变量中 -

    userprofile = UserProfile(form.username.data)
    userprofile = UserProfile.query.filter_by(nickname=form.username.data).first()
    session['wm']=userprofile.wm

But it fails with message like : 但它失败的消息如下:

     session['wm']=userprofile.wm
     AttributeError: 'NoneType' object has no attribute 'wm'

Mysql db: Mysql db:

mysql> desc UserProfile;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| nickname   | varchar(40) | NO   | PRI | NULL    |       |
| wm         | tinyint(1)  | YES  |     | NULL    |       |

It has a record too. 它也有记录。

Thanks for any help. 谢谢你的帮助。

You need to actually add your new UserProfile object to the database first: 您需要首先新的UserProfile对象首先添加到数据库:

userprofile = UserProfile(form.username.data)
db.session.add(userprofile)

See the Flask-SQLAlchemy documentation on insertion : 有关插入的信息,请参阅Flask-SQLAlchemy文档

Before you add the object to the session, SQLAlchemy basically does not plan on adding it to the transaction. 在将对象添加到会话之前,SQLAlchemy基本上不打算将其添加到事务中。 That is good because you can still discard the changes. 这很好,因为您仍然可以放弃更改。 For example think about creating the post at a page but you only want to pass the post to the template for preview rendering instead of storing it in the database. 例如,考虑在页面上创建帖子,但您只想将帖子传递给模板进行预览渲染,而不是将其存储在数据库中。

The add() function call then adds the object. 然后add()函数调用添加对象。

After adding you need to commit,to see the changes 添加后,您需要提交,以查看更改

userprofile = UserProfile(form.username.data)
db.session.add(userprofile)
db.session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM