To learn more about the concepts covered in this lesson, check out:
Refactoring Your Code
Then you use the
secrets module to randomly choose five characters from
chars and return the selection. You could accomplish a similar result by using the
random module, as before. However, the
secrets module is recommended when creating random strings that you use as secret keys.
PEP 506 introduced
secrets as the standard Python module for generating cryptographically secure random bytes and strings. Check out the Guide to Generating Random Data in Python to learn more about generating random data.
When you call
create_random_key() without any arguments, you receive a string with five characters. In your case, the string is probably different from the string seen on-screen, but it should contain uppercase letters, numbers, or both.
while loop is the most crucial part of this function. You’re calling
create_random_key() again if
key already exists in the database. Using this logic makes sure that every shortened URL exists only once.
With this function in place, update your
create_db_url() function in
crud.py. First you call
keygen.create_unique_random_key() to get a unique string for your shortened URL’s key. By calling this function, you ensure that there are no duplicate keys in the database.
Note that you’re calling
keygen.create_random_key() to construct a
secret_key string. As you saw before,
keygen.create_random_key() only creates a random string, but you don’t check if it exists in the database.
But you can be sure that
secret_key is unique because you are prefixing the string with the value of
key. So even if
keygen.create_random_key() returns an already-created string, then putting the unique key up front makes the entire string unique.
This is a great chance to use an assignment expression (
:=), otherwise known as the walrus, and streamline the
if statement. The walrus operator gives you a new syntax for assigning variables in the middle of expressions. If you’d like to know more about the walrus operator, check out this Real Python video course.
db_url is a database entry, then you return your
RedirectResponse to the
target_url. Otherwise, you call
raise_not_found(). With all these updates in place, it’s time to check if your Python URL shortener still works as expected.
Your API functions in the same way as at the end of the last step. But your code is much cleaner now. Still, you are not returning URLs, as the attributes
.admin_url would suggest. Instead, you’re only returning the keys.
Become a Member to join the conversation.