How it works...

For a management command, we need to create a Command class deriving from BaseCommand and overwriting the add_arguments() and handle() methods. The help attribute defines the help text for the management command. It can be seen when you type the following in the command line:

(myproject_env)$ python3 manage.py help import_movies_from_csv

Django management commands use the built-in argparse module to parse the passed arguments. The add_arguments() method defines what positional or named arguments should be passed to the management command. In our case, we will add a positional file_path argument of Unicode type. By nargs set to the 1 attribute, we allow only one value.

To learn about the other arguments that you can define and how to do this, refer to the official argparse documentation at https://docs.python.org/2/library/argparse.html#the-add-argument-method.

At the beginning of the handle() method, the verbosity argument is checked. Verbosity defines how much terminal output the command should provide, from 0, not giving any, to 3, providing extensive logging. You can pass this argument to the command as follows:

(myproject_env)$ python3 manage.py import_movies_from_csv 
> ../data/top-movies.csv --verbosity=0

Then, we also expect the filename as the first positional argument. The options["file_path"] returns a list of the values defined in the nargs; therefore, it is one value in this case.

We open the given file and pass its pointer to csv.readerThe first line in the file is assumed to contain headings for each of the columns, so it is skipped. Then, for each additional line in the file, we will create a new Movie object, if a matching movie doesn't exist yet. Our command only supports two levels of output verbosity, and we default the level to --verbosity=1, so the management command will print out the imported movie ranks and titles to the console, unless you set --verbosity=0.

If you want to debug the errors of a management command while developing it, pass the --traceback parameter for it. If an error occurs, you will see the full stack trace of the problem.

Assuming we invoked the command with --verbosity=1 or higher, the start of the sort of output we could expect might be as follows:

(myproject_env)$ python3 manage.py import_movies_from_csv 
> ../data/movies.csv --verbosity=1
=== Importing movies ===
1. The Shawshank Redemption
2. The Godfather
3. The Godfather: Part II
4. The Dark Knight
5. 12 Angry Men
6. Schindler's List
7. The Lord of the Rings: The Return of the King
8. Pulp Fiction
9. The Good, the Bad and the Ugly
10. Fight Club
...

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.254.231