I have apps that solve the same problem and I rely on IntegrityError. I simply catch it and return the information to the user that the username is already taken. Someone else here suggested you should check if the username exists first, but that is not as good a solution. What if another process registers that username between your check and commit? While this may seem unlikely, depending on the rate of new user generation, it doesn't make sense to do that if the naturally transactional and robust way is to rely on IntegrityError for no extra code required, especially since you can't lock unexisting rows for update:

try:
    session.add(user)
except IntegrityError as e:
    transaction.abort()
    if "user_name_key" in e:
        print "The username already exists"
        # Or whatever
    elif "email_key" in e:
        print "The email aready exists."
        # Or whatever

.oO V Oo.


On 10/27/2011 02:51 PM, Mark Erbaugh wrote:
I'm developing a Pyramid app with SQLAlchemy.

I have a user registration page where user picks their user name and enter 
other user-related information. The user name is the primary key in the 
corresponding table. If the user picks a user name that is already in use by 
another user, I need to inform the user of the fact and ask them to pick a 
different user name. Pyramid apparently does an automatic commit of any changes 
the the DBSession at the end of processing a page. When the record with the 
duplicate primary key is inserted, SQLAlchemy raises an IntegrityError 
exception as expected.

My question is should I manually commit the DBsession inside a try ... except 
block to catch and handle the exception in my page processing code, or should I 
let the automatic commit fail and somehow trap the exception and process it 
somewhere else, and if so, how and where do I trap the exception?

Thanks,
Mark


--
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en.

Reply via email to