简体   繁体   中英

Generating unique usernames from an email list for creating new users in django application

I am importing contacts from gmail. c_lst is the list that has the names and email address in a dictionary as follows - [{'name': u'fn1 ln1', 'emails': [u'email1@gmail.com']}, {'name': u'fn2 ln2', 'emails': [u'email2@gmail.com']},.

There are two problems with importing contacts:

  1. Some of the contacts that I might be importing, might already be present in the database, in that case, I do not want to add another contact.

  2. Unique usernames. There is a possibility of two emails being same, except the domain names. eg. email@gmail.com and then email@outlook.com in that case, I need to have distinct usernames so the first username would be like email, and the second one would be email1.

I have implemented both of them, and commented for making things clear. Can there be more pythonic way of doing it?

for contact in c_lst:
email = contact.get('emails')[0]
name = contact.get('name').split(' ')
first_name, last_name = name[0], name[-1]
try:
    # check if there is already a user, with that email address
    # if yes then ignore.
    u = Users.objects.get(email = email)
    print "user exists"
except:
    while True:
        username = email.split('@')[0]
        name, idx = username, 1 
        try:
            # user with current username exists, so add numeral
            Users.objects.get(username = username)
            name = username + str(idx)
        except User.DoesNotExist:
            username = name
            u = User.objects.create(username = username, email = email, first_name = first_name, last_name = last_name)
            u.save()
            break

Please let me know, of any other/better flow/approach.

For generating usernames, one might advice generating random numbers, but its okay for me to go sequentially, as it is only one time activity.

The one thing I would like to change is to handle the first except explicitly. Since you are using:

u = Users.objects.get(email=email)  # don't add space before and after "=" in argument

It could raise a MultipleObjectsReturned exception then create an infinite loop in the current except block.

So you should at least change your code to:

# ... your code ...
first_name, last_name = name[0], name[-1]
try:
    u = Users.objects.get(email=email)
except User.DoesNotExist:
    # ... your code ....
except User.MultipleObjectsReturned:
    # handle this case differently ?

Well your might want to handle the second try except block similarly but that's your choice.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM