Django regularly executes tasks, while django executes tasks

Source: Internet
Author: User

Django regularly executes tasks, while django executes tasks

To regularly execute tasks in the django project, such as capturing data and refreshing the database at a certain point in time every day, you can refer to the stackoverflow method to compile a manage first. py command, and then use crontab to regularly execute this command.

Customize the manage. py command

The app can use manage. py to register its own commands. For example, to customize a closepoll command in the polls app, you must first add a management/commands to the polls folder.Directory:

polls/    __init__.py    models.py    management/        __init__.py        commands/            __init__.py            _private.py            closepoll.py    tests.py    views.py

In this way, every py file not starting with "_" in the commands directory is registered as a manage. py command.

In python 2, note that the management and commands directories must contain a _ init _. py file.

The closepoll. py file must define a class Command that inherits the BaseCommand.

from django.core.management.base import BaseCommand, CommandErrorfrom polls.models import Pollclass Command(BaseCommand):    help = 'Closes the specified poll for voting'    def add_arguments(self, parser):        parser.add_argument('poll_id', nargs='+', type=int)    def handle(self, *args, **options):        for poll_id in options['poll_id']:            try:                poll = Poll.objects.get(pk=poll_id)            except Poll.DoesNotExist:                raise CommandError('Poll "%s" does not exist' % poll_id)            poll.opened = False            poll.save()            self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

Before django1.8, the command line parsing of the manage. py command is based on the optparse library, where the location parameter is passed to * args, and the optional parameter is passed to ** options. After 1.8, the command line Parsing is based on the argparse library, and the parameters are passed to ** options.

The location parameter poll_id is added to the closepoll. py file. The number is one or more and the type is INTEGER:

def add_arguments(self, parser):        parser.add_argument('poll_id', nargs='+', type=int)

The closepoll command can be used as follows:

python manage.py closepoll <poll_id>

Self. stdout and self. stderr can display the information you want to display in the console.

You can add optional parameters:

class Command(BaseCommand):    def add_arguments(self, parser):        # Positional arguments        parser.add_argument('poll_id', nargs='+', type=int)        # Named (optional) arguments        parser.add_argument('--delete',            action='store_true',            dest='delete',            default=False,            help='Delete poll instead of closing it')    def handle(self, *args, **options):        # ...        if options['delete']:            poll.delete()

Add an optional parameter named -- delete with the value True.

Execute python manage. py closepoll 1 2 3 -- delete to delete poll with id 1, 2, and 3.

When python manage. py closepoll 1 2 3 is executed, the -- delete value defaults to False.

Use crontab to regularly execute the manage. py command

Use the crontab-e command to edit cron. The window will prompt:

# m h  dom mon dow   command

In a month (mon), several minutes of a day (dom) or day of the week (dow) (h, 24-hour) (m) to execute a command ), * indicates any time.

* */2 * * * python manage.py closepoll <poll_id>  

This means that the closepoll command is executed every two hours. To prevent the manage. py file from being found, you can write the real address of the manage. py file.

Save and restart cron:

sudo service cron restart

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.