簡體   English   中英

從電子郵件列表中生成唯一的用戶名,以便在Django應用程序中創建新用戶

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

我正在從gmail導入聯系人。 c_lst是在字典中具有名稱和電子郵件地址的列表,如下所示- [{'name': u'fn1 ln1', 'emails': [u'email1@gmail.com']}, {'name': u'fn2 ln2', 'emails': [u'email2@gmail.com']},.

導入聯系人有兩個問題:

  1. 有的,我可能會被導入,可能已經存在於數據庫中,在這種情況下,接觸的,我希望添加其他聯系人。

  2. 唯一的用戶名。 除域名外,可能會有兩封電子郵件相同。 例如。 如果是email@gmail.com,然后是email@outlook.com,則我需要使用不同的用戶名,因此第一個用戶名將類似於email,第二個用戶名將是email1。

我已經實現了它們兩個,並評論說清楚了。 可以使用更多的pythonic方法嗎?

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

請讓我知道其他/更好的流程/方法。

對於生成用戶名,可能建議生成隨機數,但我可以按順序進行,因為這只是一次活動。

我想更改的一件事是處理第一個, except明確。 由於您正在使用:

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

它可能會引發MultipleObjectsReturned異常,然后在當前的except塊中創建一個無限循環。

因此,您至少應將代碼更改為:

# ... 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 ?

好吧,您可能想要處理第二次try except類似地阻止,但這是您的選擇。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM