1

我有以下管理命令(website.py)

from __future__ import absolute_import
from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def run_from_argv(self, argv):
        self._argv = argv
        self.execute()

    def handle(self, *args, **options):
        from scrapy.cmdline import execute
        execute(self._argv[1:])

我想通过 URL 执行这个命令:/crawl/update-now/ 视图是:

from django.core import management

def update_index(request):
    management.call_command('website', 'crawl spider')

但它不起作用:

Command' object has no attribute '_argv'
4

1 回答 1

1

I think problem is that run_from_argv is internal Django method and called by django.core.management.ManagementUtility. And you should not implement it by yourself, self._argv is not set anywhere. Arguments are already available in handle().

And your approach has some disadvantages.

First of all, due to synchronous nature of Django, if your URL is "heavy" it can take a lot of time to get it and parse. Instead of it, I'm strongly recommend you to take a look at Celery. It is more "right" way to execute tasks from views and has no problems with performance.

于 2013-01-15T10:46:25.677 回答