python - flask : retrieve data from db and store it session

标签 python sqlalchemy flask

我有 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)

在用户登录期间 - 我正在尝试从数据库中检索记录 并将其值存储在 session 变量中 -

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

但它失败并显示如下消息:

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

Mysql 数据库:

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

它也有记录。

感谢您的帮助。

最佳答案

您实际上需要先添加您的新 UserProfile 对象到数据库:

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

参见 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.

关于python - flask : retrieve data from db and store it session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599519/

相关文章:

python - 如何检查主机的 DNS TXT 记录值?

python - 参数错误 : relationship expects a class or mapper argument

Python结构体格式错误

异常中的Python字符串转换为元组

python - 向 SQLAlchemy 查询添加上下文注释

python - SqlAlchemy如何查询列A==a和B==b和A==b和B==a

python - 如何在 python flask 应用程序中安全地共享全局变量(缓存的公共(public)证书)

python - 在需要可扩展的 Python Web 应用程序中解开大量数据是否可行?

python - Flask-WTFoms 字段中的自定义参数

python - 无法让 python 跟随 base32 编码