-1

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?

Samuel Davies
  • 54
  • 1
  • 5
  • 4
    It’s not clear what the parameters are for this. Is it something a user should remember and use, or just a primary key in the database? If it’s for users, a common approach is to add numbers to the end, but that’s not super satisfying for users. You could also let users pick until they find a unique one. – Mark Mar 05 '23 at 16:28
  • @Mark I have just updated the problem to hopefully be more clear. – Samuel Davies Mar 05 '23 at 17:13
  • @SamuelDavies If either of the answers below solved your issue, then consider marking the one that best helped you as correct. This would help guide others with the same issue in the future. – Michael M. Mar 07 '23 at 01:20
  • @MichaelM. The answer that I was going to accept has been deleted. – Samuel Davies Mar 07 '23 at 14:36

2 Answers2

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.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
-1

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.

Wijze
  • 94
  • 5