Generating and using tokens
Now, we will launch our default Python interactive shell in our virtual environment and make all the Django project modules available to write code that will generate a token for an existing user. We will do this to understand how the token generation works.
Run the following command to launch the interactive shell. Make sure you are within the restful01
folder in the terminal, Command Prompt, or Windows Powershell:
python manage.py shell
You will notice that a line that says (InteractiveConsole)
is displayed after the usual lines that introduce your default Python interactive shell. Enter the following code in the Python interactive shell to import all the things we will need to retrieve a User
instance and generate a new token. The code file for the sample is included in the hillar_django_restful_08_02
folder, in the restful01/tokens_test_01.py
file.
from rest_framework.authtoken.models import Token from django.contrib.auth.models import User
Enter the following...