[英]Python Flask - Like a post without reloading the page
Thanks in advance for your help!在此先感谢您的帮助!
I have a flask website, on which the users can post some programming code snippets, like them or write comments under each post.我有一个flask网站,用户可以在上面发布一些编程代码片段,喜欢它们或在每个帖子下写评论。 For every action, fe deleting a post or liking a post, I've defined a route, which checks if the user has enought rights to perform the action and so on.对于每个操作,删除帖子或点赞帖子,我都定义了一个路由,它检查用户是否有足够的权限来执行该操作等等。 This works fine.这工作正常。
What I would like to achieve:我想达到的目标:
I want to be able to use those functionalities, without having to reload the page.我希望能够使用这些功能,而无需重新加载页面。 I've tried this with an ajax request, but could not figure it out.我已经用 ajax 请求尝试过这个,但无法弄清楚。 Here are some of these routes:以下是其中一些路线:
def delete_comment(id):
comment = Comment.query.get_or_404(id)
post = Post.query.get_or_404(comment.post_id)
if comment.user != current_user and post.author != current_user:
abort(403)
db.session.delete(comment)
db.session.commit()
flash('The comment has been deleted!', 'success')
return redirect(url_for('main.home'))
If I delete this comment, I get redirected to my homepage.如果我删除此评论,我将被重定向到我的主页。 Like this, you can't unlike a post if you've accidentally liked it and so on.像这样,如果您不小心喜欢了某个帖子等等,您就无法对它点赞。 Additionally, if the user has scrolled to the 20th post, it is anoying to scroll down again.此外,如果用户已经滚动到第 20 个帖子,再次向下滚动会很烦人。
How could I solve this problem?我怎么能解决这个问题?
For these types of requests, I've found javascript combined with a REST API endpoint work well - ie create a REST endpoint that will do the like/dislike and return a response, and have the button/javascript make the REST call with a simple post or get, and modify the thing you want it to.对于这些类型的请求,我发现 javascript 与 REST API 端点的结合效果很好 - 即创建一个 REST 端点,它将执行喜欢/不喜欢并返回响应,并让按钮/javascript 使用简单的 REST 调用发布或获取,并修改您想要的内容。
@app.route('/api/v1/status', methods=['GET'])
def get_status():
json_data = json.dumps({'status': get_status()})
return json_data
Similarly you can do this for posts with buttons同样,您可以对带有按钮的帖子执行此操作
@app.route('/api/v1/button_update', methods=['PUT'])
def update_button():
json_data = json.dumps({'status': update_db_state()})
return json_data
For the json, you'll have to trudge through that on your own because it will depend entirely on your page structure how you pull and update those values, what libraries you're using, etc.对于 json,您必须自己艰难地完成它,因为这完全取决于您的页面结构,您如何提取和更新这些值,您正在使用哪些库等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.