Sto creando un progetto del forum utilizzando Flask e gestendo tutti gli utenti, thread, post, ecc. Usando Flask-SQLAlchemy. Tuttavia, ho scoperto che quando provo a fare x (ad esempio, modifica un post), ottengo un InvalidRequestError se tento di fare qualsiasi altra cosa (ad esempio, elimina il post).Flask-SQLAlchemy InvalidRequestError: L'oggetto è già collegato alla sessione
Per la modifica di un post,
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', id=id, t_id=t_id))
e l'eliminazione di un post,
@app.route('/forum=<id>/thr=<t_id>/p=<p_id>/delete', methods=['GET','POST'])
def post_delete(id, t_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', id=id, t_id=t_id))
else:
flash('Access denied.')
return redirect(url_for('thread', id=id, t_id=t_id))
e la pubblicazione di un post
@app.route('/forum/id=<id>/thr=<t_id>', methods=['GET','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', id=id, t_id=t_id))
return render_template('thread.html', forum=forum, thread=thread, posts=posts, form=form, title=thread.title)
Purtroppo, l'unico modo sicuro per rendere questo problema risolvere è di per sé resettare lo script che esegue effettivamente l'app, run.py
#!bin/python
from app import app
app.run(debug=True,host='0.0.0.0')
Sembra che WhooshAlchemy sia stato effettivamente il problema. Per quanto riguarda la notazione, è solo una scorciatoia per "thr =". –
Ganye
Intendevo la parte "thr =". Ma immagino che potresti fare/thr = 44/p = 32/c = 21 tipi di formato url, ho appena trovato strano tutto qui. Sono contento di aver capito il problema però. – Dexter
Questo è esattamente quello che è; per esempio, un thread specifico (8) in un forum (1) crea l'url "/ forum/id = 1/thr = 8". – Ganye