加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Flask-SQLAlchemy InvalidRequestError:对象已附加到会话

发布时间:2020-12-16 21:39:02 所属栏目:Python 来源:网络整理
导读:我正在使用Flask创建一个论坛项目,并使用Flask-SQLAlchemy管理所有用户,线程,帖子等.但是,我发现当我尝试执行x(例如编辑帖子)时,如果我尝试执行其他操作(例如删除帖子),则会收到InvalidRequestError. 要编辑帖子, def post_edit(id,t_id,p_id): post = Post.
我正在使用Flask创建一个论坛项目,并使用Flask-SQLAlchemy管理所有用户,线程,帖子等.但是,我发现当我尝试执行x(例如编辑帖子)时,如果我尝试执行其他操作(例如删除帖子),则会收到InvalidRequestError.

要编辑帖子,

def post_edit(id,t_id,p_id):
  post = Post.query.filter_by(id=p_id).first()
  if post.author.username == g.user.username:
    form = PostForm(body=post.body)
    if form.validate_on_submit():
      post.body = form.body.data
      db.session.commit()
      return redirect(url_for('thread',id=id,t_id=t_id))
    return render_template('post_edit.html',form=form,title='Edit')
  else:
    flash('Access denied.')
    return redirect(url_for('thread',t_id=t_id))

并删除帖子,

@app.route('/forum=<id>/thr=<t_id>/p=<p_id>/delete',methods=['GET','POST'])
def post_delete(id,p_id):
  post = Post.query.filter_by(id=p_id).first()
  if post.author.username == g.user.username:
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('thread',t_id=t_id))
  else:
    flash('Access denied.')
    return redirect(url_for('thread',t_id=t_id))

并张贴帖子

@app.route('/forum/id=<id>/thr=<t_id>','POST'])
def thread(id,t_id):
  forum = Forum.query.filter_by(id=id).first()
  thread = Thread.query.filter_by(id=t_id).first()
  posts = Post.query.filter_by(thread=thread).all()
  form = PostForm()
  if form.validate_on_submit():
    post = Post(body=form.body.data,timestamp=datetime.utcnow(),thread=thread,author=g.user)
    db.session.add(post)
    db.session.commit()
    return redirect(url_for('thread',t_id=t_id))
  return render_template('thread.html',forum=forum,posts=posts,title=thread.title)

不幸的是,解决这个问题的唯一可靠方法是重置实际运行应用程序的脚本run.py.

#!bin/python

from app import app
app.run(debug=True,host='0.0.0.0')

解决方法

您使用的是WooshAlchemy,因为它可能是您问题的一部分. Described here

他描述了需要修改WooshAlchemy扩展的“修复”.

通常虽然它可能意味着您调用Post模型对象然后使用“session.add”附加它,然后尝试“session.delete”或在同一对象上执行另一个“session.add”.

你的请求路由也有点奇怪我从未见过“thr =< t_id>” Flask之前的符号类型.这对你有用吗?

http://flask.pocoo.org/docs/quickstart/#variable-rules

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读