简体   繁体   中英

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. 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. 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.

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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM