【发布时间】:2020-10-14 10:09:02
【问题描述】:
我正在使用flask和pymongo进行一个项目,我有一个用户集合和一个电影集合,其中的实例如下:
user = {"Email":"user@gmail.com" , "Comments":[" Hobbit 2013 :good movie" , " Hobbit 2013 :bad movie" , " Spiderman 2020 :very good"]}
我还有一个电影集合,其中的电影实例如下:
movie = {"title":"Hobbit" , "year":"2013" , "comments":["Hobbit 2013 user@gmail.com:good movie"] }
我正在使用 jinja 2 模板为特定电影提交新标题,如果有任何用户评论过该电影,我希望每个评论过特定电影的用户在他的 cmets 中都有新电影名称 前任。 Hobbit -> Avengers 然后用于上述用户实例
`user = {"Email":"user@gmail.com" , "Comments":[" Avengers 2013 :good movie" , " Avengers 2013 :bad movie" , " Spiderman 2020 :very good"]}`
`movie = {"title":"Avengers" , "year":"2013" , "comments":["Avengers 2013 user@gmail.com:good movie"] }` #obviously a movie can have more comments from users not just one
使用烧瓶端点,我成功更改了电影标题,但是我无法更改旧电影标题所在的任何用户评论,因为标题与我的代码无关
这是我的终点。我从 jinja2 表单中获得了新标题,然后尝试用新的 .然后我得到错误
pymongo.errors.InvalidOperation: cannot set options after executing query
我的代码:
@app.route('/executemovieupdate' , methods = ['GET', 'POST'])
def execute_movie_update():
if 'Email' in session and 'User' in session:
email = session['Email']
user = session['User']
if user == 'Admin':
if 'Movie' in session and 'Movie_year' in session and 'Movie_plot' in session:
movie = session['Movie']
old_movie = str(movie) #store old movie title
print("old movie is " , old_movie)
year = session['Movie_year']
plot = session['Movie_plot']
tainia = movies.find_one({'title':movie , "year":year})
if request.method == 'POST':
new_title = request.form.get('new-title') #get the new title from jinja2 template
if new_title:
print("update the title")
movies.update_one({"title":movie , "year":year} , {"$set":{"title":new_title} } ) #the title is updated succesfully for the movie
session['Movie'] = new_title
movie = session['Movie']
user_list = users.find({})
for idxu, usr in enumerate(user_list): #this is where i try to change the title in the user comments
for idxc, comment in enumerate(usr['Comments']):
if old_movie in comment:
print("old comment here")
print(comment)
user_list[idxu]['Comments'][idxc] = comment.replace(old_movie ,new_title) #this is the line where the error occurs
print(comment) # the new comment is printed
return ''' movie has been updated '''
else:
return render_template('movie-update.html' , movie = tainia)
else:
return redirect(url_for('admin.html'))
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
感谢您对这个问题的帮助。提前谢谢你。
【问题讨论】:
标签: python string mongodb flask pymongo