You must have used createsuperuser
command in your Django application at one or another time. If not then I am sure you must have used makemigrations
or migrate
commands in your project. Yes? Yes.
So these commands, also called as management commands are used to execute some piece of code from the command line.
In this article, We will see how to create your own command.
Let's say you have a project where you need to perform some tasks periodically.
For example, updating the database column after fetching data from some other server, sending lots of emails, taking the backup of your database, etc, etc.
- Create a directory in your application and name it management
.
- Create a blank __init__.py
file inside it.
- Create a directory named as commands
inside management
directory.
- Create a blank __init__.py
file inside commands directory.
myapp |-management | |-commands | |-__init__.py | |-mycommand.py |-__init__.py
- Inside commands
directory create a file with the name of your command. Let's say mycommand.py
.
- Add below code to this file.
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Command to do........' def add_argument(self, parser): pass def handle(self, *args, **options): try: # your logic here print("I am here") except Exception as e: CommandError(repr(e))
Command
which extends BaseCommand
.
add_argument
function is used to add the arguments to command on the command line.$ python manage.py mycommand
def add_arguments(self, parser): parser.add_argument('msg', nargs='+', type=str)
Now you may use this variable msg
in your command.
def handle(self, *args, **options): try: # your logic here msg = options["msg"] print(msg) print("I am here") except Exception as e: CommandError(repr(e))
You can use this command in crontab to execute it periodically.
Read this article on how to schedule a task on pythonanywhere.com server.