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:
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.
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.