Simone Marzola avatar Simone Marzola committed 5f59c2e

catch IntegrityErrors in vote transaction commit and redirect to referer flashing error message

Comments (0)

Files changed (1)

tgcomments/controllers/root.py

 # -*- coding: utf-8 -*-
 """Main Controller"""
+from sqlalchemy.exc import IntegrityError
 
 from tg import TGController
 from tg import expose, flash, require, url, lurl, request, redirect, validate, config
 from tgcomments import model
 from tgcomments.model import DBSession, Comment, CommentVote
 from tgcomments.lib import get_user_gravatar, notify_comment_on_facebook, make_fake_comment_entity, FakeCommentEntity
+import transaction
 
 try:
     from tg import predicates
                'value':Int(not_empty=True)},
               error_handler=fail_with(403))
     def vote(self, comment, value):
+        transaction.begin()
         user = request.identity['user']
-
-        vote = DBSession.query(CommentVote).filter_by(comment=comment).filter_by(user=user).first()
-        if not vote:
+        vote = DBSession.query(CommentVote).filter_by(comment=comment, user=user).first()
+        if vote is None:
             vote = CommentVote(comment=comment, user=user)
             DBSession.add(vote)
 
         max_vote_value = votes_range[1]
 
         vote.value = min(max(min_vote_value, value), max_vote_value)
+
+        try:
+            DBSession.flush()
+            transaction.commit()
+        except IntegrityError:
+            return back_to_referer(success=False)
+
         flash(_('Thanks for your vote!'))
         return back_to_referer(success=True)
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.