skip to Main Content

I am using Python to interact with a MySQL database. I have a function that allows a user to create an account. The parameters of this function are their full name, email, and password. These parameters are the input fields required to create an account.

Based on the “full name” or “email” parameter I would like to generate a unique username for a user. This username can then be changed at a later date by the user. Usernames will be used to lookup other users (by the use of a search function etc) and so should be in a more human readable format than that of a UUID etc. What is the best approach for this?

Should I generate a list of random names (using some random function) and then iterate through the array until I find the first username that is not found in the database, then assign it to the user? Or is there a better, more efficient approach?

2

Answers


  1. If you don’t need usernames to be completely human-friendly, then you’re probably best off using a UUID. You can generate one like this with the built-in uuid module:

    import uuid
    
    username = uuid.uuid4()
    print(username)
    

    The chance that the same two identical UUIDs are generated is astronomically unlikely. Because of this, you don’t need to check if it already exists in the database, however, there’s no harm in doing so.

    Login or Signup to reply.
  2. Please don’t use password as a parameter to generate an username 🙂

    • You can use email-address as an user identifier, this is commonly used. If you like you can also give the user the option to select another name for how there username will be displayed to other users but keep the email-address as your way of identifying users
    • Otherwise you can generate a bunch of possible options depending on their name and email-address and check if they already exist. You could possibly let the user choose from the ones that are not taken.

    You can also just let the user choose their username but check if it is already taken.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search