Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created March 27, 2017 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/49eecf1bb26321be96eff313f73f034d to your computer and use it in GitHub Desktop.
Save joelburton/49eecf1bb26321be96eff313f73f034d to your computer and use it in GitHub Desktop.
AJAX movie rating snippet
@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