django celery简单 例子

django celery简单 例子

https://docs.celeryq.dev/en/latest/django/first-steps-with-django.html

pip list
pip install Django4.2.3
pip install redis
4.6.0
pip install celery5.3.1
pip install SQLAlchemy
2.0.17

source demo1_venv/bin/activate

django-admin startproject proj
在这里插入图片描述
cd proj
python manage.py startapp demoapp
在这里插入图片描述
cd proj

vi settings.py
在最前面添加下面的语句:

import os
# Celery settings

CELERY_BROKER_URL = 'redis://127.0.0.1:6379/4'

#: Only add pickle to this list if your broker is secured
#: from unwanted access (see userguide/security.html)
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/3'
CELERY_TASK_SERIALIZER = 'json'

然后在settings的
a

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'demoapp',
]

b

vi __init__.py

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

新建文件celery.py
vi celery.py


import os
  
from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('proj')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django apps.
app.autodiscover_tasks()


@app.task(bind=True, ignore_result=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

cd …/demoapp
vi models.py

from django.db import models
class Widget(models.Model):
    name = models.CharField(max_length=140)

cat tasks.py

# Create your tasks here

from demoapp.models import Widget

from celery import shared_task


@shared_task
def add(x, y):
    return x + y


@shared_task
def mul(x, y):
    return x * y


@shared_task
def xsum(numbers):
    return sum(numbers)


@shared_task
def count_widgets():
    return Widget.objects.count()


@shared_task
def rename_widget(widget_id, name):
    w = Widget.objects.get(id=widget_id)
    w.name = name
    w.save()

celery -A proj worker -l INFO

python ./manage.py shell
>>> from demoapp.tasks import add, mul, xsum
>>> res = add.delay(2,3)
>>> res.get()
5
>>> 

可以使用了
在这里插入图片描述

### 配置Celery 为了使Django项目能够利用Celery执行异步任务,需先完成必要的环境搭建工作。这包括安装所需的软件包以及设置相应的配置项。 #### 安装依赖库 通过pip工具来安装`celery`及其消息代理(如Redis),命令如下: ```bash pip install celery redis ``` #### 设置Django项目的Celery实例 创建一个新的Python文件用于初始化Celery应用,在此假设命名为`celery.py`并放置于与`manage.py`同级目录下[^2]。 ```python from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings') app = Celery('your_project_name') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() ``` 在此基础上还需修改`__init__.py`以确保当Django启动时自动加载Celery应用程序: ```python # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) ``` #### 更新Settings Configuration 编辑`settings.py`加入Celery的相关参数定义,例如指定使用的Broker URL和Result Backend等选项[^1]。 ```python CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' # Optional configurations, see http://celery.readthedocs.org/en/latest/configuration.html CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' ``` 以上步骤完成后便可以在任意Django App内开发具体的异步任务函数了。 ### 编写异步任务 在期望添加异步操作的应用程序中新建tasks模块,并编写具体业务逻辑的任务方法。下面给出一个简单例子展示如何发送邮件作为后台作业处理: ```python from celery import shared_task from django.core.mail import send_mail @shared_task def send_email(subject, message, recipient_list): """Send an email asynchronously.""" try: result = send_mail( subject=subject, message=message, from_email=None, # Use DEFAULT_FROM_EMAIL setting recipient_list=recipient_list, fail_silently=False, ) return f'Successfully sent {result} emails.' except Exception as e: raise ValueError(f"Failed to send mail due to error: {str(e)}") ``` 此时调用该任务的方式有两种:一种是在视图或其他地方直接触发;另一种则是借助调度器定期运行特定任务。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值