You must have used createsuperuser command in your django application at one or other 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 command line. In this article I will tell you how to create your own command.
myapp |-management | |-commands | |-__init__.py | |-mycommand.py |-__init__.py- Inside commands directory create a file with name of your command. Lets 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))- We must define a class with name Command which extends BaseCommand . - Here add_argument function is used to add the arguments to command on command line. - Write whatever login you want to execute in handle function. Pro tip here : If your logic is very lengthy, you can write it as a separate service and call that service function in your handle function. - Save the files and on terminal execute your command. You will see the output on the screen.
$ 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 is periodically. Read this article on how to schedule a task on pythonanywhere.com server.