Created
March 27, 2017 05:23
-
-
Save joelburton/49eecf1bb26321be96eff313f73f034d to your computer and use it in GitHub Desktop.
AJAX movie rating snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.route("/movies/ajax/<int:movie_id>", methods=['POST']) | |
def movie_detail_ajax_process(movie_id): | |
"""Add/edit a rating.""" | |
# Get form variables | |
score = int(request.form["score"]) | |
user_id = session.get("user_id") | |
if not user_id: | |
raise Exception("No user logged in.") | |
rating = Rating.query.filter_by(user_id=user_id, movie_id=movie_id).first() | |
if rating: | |
rating.score = score | |
added = False | |
else: | |
rating = Rating(user_id=user_id, movie_id=movie_id, score=score) | |
added = True | |
db.session.add(rating) | |
db.session.commit() | |
try: | |
1/0 | |
except ZeroDivisionError: | |
return jsonify({"status": "error", "detail": "omg zero"}) | |
# if True: | |
# return jsonify({"status": "error", "detail": "too many ratings"}) | |
if added: | |
return jsonify({"status": "added", "score": score}) | |
else: | |
return jsonify({"status": "updated", "score": score}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment