简体   繁体   中英

Flask : retrieve data from db and store it session

I have db.model like :

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 -

    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> 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(form.username.data)
db.session.add(userprofile)

See the Flask-SQLAlchemy documentation on insertion :

Before you add the object to the session, SQLAlchemy basically does not plan on adding it to the transaction. 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.

After adding you need to commit,to see the changes

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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