Django celery异步执行
把python的那套,复制到Django项目可以执行
但是从view执行http://127.0.0.1:8080/async_add/ 报错
from django.http import HttpResponse
from file_downloads.tasks import add
def async_add(request):
result = add.delay(4, 4)
print(result.id) # 打印任务ID
print('here2')
print(result.__dict__) # 结果信息
print('here3')
print(result.successful()) # 是否成功
print(result.failed()) # 是否失败
print(result.ready()) # 是否执行完成
print(result.state) # 状态 PENDING -> STARTED -> SUCCESS/FAIL
# 你可以使用result.ready()来检查任务是否已经完成,然后使用result.get()获取结果。
value = result.get() # 任务返回值
print(result.get()) # 阻塞直到结果准备就绪或超时
return HttpResponse("Task queued.")
另寻思路
Django Celery, 世界上最牛逼的Django异步任务队列库
下载
pip install django-celery-results
pip install django-celery-beatpip install diango-redis
1、__init__.py
from .celery import app as celery_app
__all__ = ('celery_app',)
不配置报错
2、celery.py
# 导入Celery应用
from celery import Celery
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'download_service.settings')
# 创建Celery应用
app = Celery('download_service')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
3、setting
# Celery配置
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'django-db'
INSTALLED_APPS += ('django_celery_results','django_celery_beat')
4、task
# tasks.py
from celery import shared_task
@shared_task
def my_task(param1, param2):
# 任务逻辑
result = param1 + param2
return result
5、url与view
path('async_add/', async_add),
from django.http import HttpResponse
from file_downloads.tasks import my_task
def async_add(request):
result = my_task.delay(4, 5)
print(result.id) # 打印任务ID
print('here2')
print(result.__dict__) # 结果信息
print('here3')
print(result.successful()) # 是否成功
print(result.failed()) # 是否失败
print(result.ready()) # 是否执行完成
print(result.state) # 状态 PENDING -> STARTED -> SUCCESS/FAIL
print(result.get()) # 阻塞直到结果准备就绪或超时
return HttpResponse("Task queued.")
6、执行迁移
python manage.py makemigrations
python manage.py migrate
8、启动redis与celery,django
redis-server
celery -A download_service worker -l info -P eventlet 项目根目录下执行
python manage.py runserver 8080
9、访问url http://127.0.0.1:8080/async_add/
原文地址:https://blog.csdn.net/daxiashangxian/article/details/144310490
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!