Python: Howto Use Just Email Addresses as User Names in TurboGears 2.0

I have been working on a few TurboGears applications lately, which is obvious being how much I'm writing about it. And for this article I'm going to touch on how you can use email addresses for user names.

Note: This article assumes you are familiar with TurboGears and doesn't really go into much detail of TurboGears.

Note: We will refer to the TG2 application as 'my_app' in the examples.

The Problem

Well, I wouldn't really call it a problem, however for almost all applications I would want to write I prefer to just use email addresses for user names. The thing is, you want to ensure the User.email_address is unique, but also the User.user_name is unique as well. Why bother with both, and making your users remember a user name that probably won't be used other wise throughout your application?

If you want to use email addresses as user names, the following sections outlines how.

And The Resolution

The modifications to make this happen are actually really simple. Really all you need to do is create a synonym for 'email_address' to the 'user_name' member of the User() class.

Remove the following from '/model/auth.py' under the User() class:

email_address = Column(Unicode(255), unique=True, nullable=False,
                                info={'rum': {'field':'Email'}})

Then, under the same section but towards the bottom replace it with:

def _set_user_name(self, user_name):
    self.user_name = user_name)
 
def _get_user_name(self):
    return self.user_name
 
email_address = synonym('user_name', descriptor=property(_get_user_name, _set_user_name))

You will also want to update your websetup.py... this is the default section:

    manager = model.User()
    manager.user_name = u'manager'
    manager.display_name = u'Example manager'
    manager.email_address = u'manager@somedomain.com'
    manager.password = u'managepass'
 
    editor = model.User()
    editor.user_name = u'editor'
    editor.display_name = u'Example editor'
    editor.email_address = u'editor@somedomain.com'
    editor.password = u'editpass'

You will want to change these two sections to something like:

    manager = model.User()
    manager.display_name = u'Example manager'
    manager.email_address = u'manager@somedomain.com'
    manager.password = u'managepass'
 
    editor = model.User()
    editor.display_name = u'Example editor'
    editor.email_address = u'editor@somedomain.com'
    editor.password = u'editpass'

From this point on, you can now reference the 'email_address' rather than the 'user_name' throughout your app.

Reference

TurboGears 2.0 is the next stage in TurboGears development, and provides a solid base on which the future of TurboGears will be built. The 2.0 release does not spell the end of 1.0 support, and while it's new, there are already people using it in production.