当我在 Django 中使用 Tweepy 时,芹菜没有 运行 任务

celery doesn't run task when I'm using Tweepy in Django

当我想将 tweepy 用于 celery 任务时它不会 运行 它只会给我失败

tasks.py

@shared_task(bind=True)
def retweet(self, consumer_key, consumer_secret, access_token, access_token_secret, clean_text, clean_count, clean_lang,
            sleep_time):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    for tweet in tweepy.Cursor(api.search, q=(clean_text) + " -filter:mentions", count=clean_count,lang=clean_lang).items(int(clean_count)):
        tweet.retweet()

views.py

class Retweet(FormView):
    form_class = RetweetForm
    template_name = 'retweet.html'
    success_url = reverse_lazy('tweet:done')
    def form_valid(self, form):
        user = self.request.user
        query = form.cleaned_data.get('query')
        count = form.cleaned_data.get('count')
        time = form.cleaned_data.get('sleep_time')
        lang = form.cleaned_data.get('lang')
        clean_text = BeautifulSoup(query, "lxml").text
        clean_count = BeautifulSoup(count, 'lxml').text
        sleep_time = BeautifulSoup(time, 'lxml').text
        clean_lang = BeautifulSoup(lang, 'lxml').text
        retweet.delay(user.consumer_key, user.consumer_secret, user.access_token, user.access_token_secret,
                          clean_text, clean_count, clean_lang, sleep_time)

芹菜工人错误:

The full contents of the message body was: b'\x80\x04\x95B\x01\x00\x00\x00\x00\x00\x00(\x8c\x19crR6CW6AB9MpsLkFsGLu4i1du\x94\x8c2cMEZk1z8zlSPnKlYZKTgpBXEqeZ4EMpf4HGSIe7j1adYAAwf5w\x94\x8c21157597880-a3cBcPLXFNaaeT3DYbajBdznpdGid1llqqmxEE0\x94\x8c-LBmrhuR6MWIvJ1YhLpR9DDUIxlqBwumfbsMxlmZagZtC1\x94\x8cE\xd9\x87\xd9\x88\xd8\xb4 \xd9\x85\xd8\xb5\xd9\x86\xd9\x88\xd8\xb9\xdb\x8c OR \xd8\xa8\xd8\xb1\xd9\x86\xd8\xa7\xd9\x85\xd9\x87 \xd9\x86\xd9\x88\xdb\x8c\xd8\xb3\xdb\x8c OR \xd8\xa7\xdb\x8c\xd9\x84\xd8\xa7\xd9\x86 \xd9\x85\xd8\xa7\xd8\xb3\xda\xa9\x94\x8c\x013\x94\x8c\x02fa\x94\x8c\x016\x94t\x94}\x94}\x94(\x8c\tcallbacks\x94N\x8c\x08errbacks\x94N\x8c\x05chain\x94N\x8c\x05chord\x94Nu\x87\x94.' (333b) Traceback (most recent call last): File "/Users/User/PycharmProjects/twitterTest/venv/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'tweet.tasks.retweet'

表示Celery在调用时找不到任务tweet.tasks.retweet的实现。所以你也没有配置正确:

  • 芹菜 imports 例如celery_app.conf.update(imports=['tweet.tasks'])celery_app.conf.imports = ['tweet.tasks']
  • 或芹菜 include (example) 例如celery_app = Celery(..., include=['tweet.tasks'])

您必须拥有:

  • ['tweet.tasks'] 如果这是你的文件结构
.
└── tweet
    └── tasks.py
  • ['tweet'] 如果您的文件结构包含 __init__.py 导入该文件夹中的所有任务。
.
└── tweet
    ├── __init__.py
    └── tasks.py