Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Flask:从数据库中检索数据并在会话中存储_Python_Sqlalchemy_Flask - Fatal编程技术网

Python Flask:从数据库中检索数据并在会话中存储

Python Flask:从数据库中检索数据并在会话中存储,python,sqlalchemy,flask,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):

我有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['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)
见:

在将对象添加到会话之前,SQLAlchemy基本上不打算将其添加到事务中。这很好,因为您仍然可以放弃更改。例如,考虑在页面上创建帖子,但您只希望将帖子传递到模板以进行预览呈现,而不是将其存储在数据库中

然后,add函数调用添加对象

您需要首先将新的UserProfile对象添加到数据库:

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

在将对象添加到会话之前,SQLAlchemy基本上不打算将其添加到事务中。这很好,因为您仍然可以放弃更改。例如,考虑在页面上创建帖子,但您只希望将帖子传递到模板以进行预览呈现,而不是将其存储在数据库中

然后,add函数调用添加对象


添加后,您需要提交以查看更改

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

添加后,您需要提交以查看更改

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

但如果我在用户下次登录失败时添加db.session.adduserprofile,并显示类似于sqlalchemy.exc.IntegrityError:IntegrityError 1062的消息,重复条目,然后首先查询用户对象,仅当用户对象不存在时才创建一个新的条目。但是,如果我在用户下次登录时添加db.session.adduserprofile,它会失败,并显示类似sqlalchemy.exc.IntegrityError:IntegrityError 1062的消息,重复条目,然后首先查询用户对象,只有在用户对象不存在时才创建新的用户对象。