您的位置:首页 > 脚本大全 > > 正文

django响应返回的常用方法(Django异步任务之Celery的基本使用)

更多 时间:2021-11-03 15:18:06 类别:脚本大全 浏览量:839

django响应返回的常用方法

Django异步任务之Celery的基本使用

Celery

许多Django应用需要执行异步任务, 以便不耽误http request的执行. 我们也可以选择许多方法来完成异步任务, 使用Celery是一个比较好的选择, 因为Celery有着大量的社区支持, 能够完美的扩展, 和Django结合的也很好. Celery不仅能在Django中使用, 还能在其他地方被大量的使用. 因此一旦学会使用Celery, 我们可以很方便的在其他项目中使用它.

celery 是一个用于实现异步任务的库, 在很多项目中都使用它, 它和 django 融合使用很完美. 使用 celery 可以在实现 http request请求返回 view 前做一些我们想做的而且耗时的事情而不会让用户等待太久

环境

django 版本 == 1.11.6

celery 版本 == 3.1.25

安装

  • ?
  • 1
  • 2
  • pip install django-celery
  • pip install celery
  • 首先需要将 celery 添加到 django 项目的 settings 里, celery 任务和 django 需要一个 中间人(broker),,这里使用的是 django 自带的 broker, 但在生产中一般使用 rabbitmq, Redis 等,在 INSTALLED_APP 中需要添加 djcelery 和 kombu.transport.django, 还有 app 应用。

    - project/project/ settings.py:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • import djcelery
  •  
  • djcelery.setup_loader()
  • BROKER_URL = 'django://'
  •  
  • INSTALLED_APP = (
  •  ...
  •  'app'
  •  'djcelery',
  •  'kombu.transport.django',
  • )
  • 新建 celery.py 创建一个 celery 应用,并添加以下内容

    - project/project/ celery.py:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • # 相对路径导入, 防止导入 celery 时冲突
  • from __future__ import absolute_import
  • import os
  • from celery import Celery
  • from django.conf import settings
  •  
  • # 让 celery 能找到 django 项目
  • os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
  • # 创建一个 celery 应用
  • app = Celery('project')
  •  
  • # 导入配置
  • app.config_from_object('django.conf:settings')
  • # 自动发现 task
  • app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
  •  
  • @app.task(bind=True)
  • def debug_task(self):
  •  
  •  print('Request: {0!r}'.format(self.request))
  • - project/project/ __init__.py:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • from __future__ import absolute_import
  •  
  • # 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
  • 在 django app 中添加任务,文件名必须是 tasks.py, 在普通 python 函数前加一个 @task() 装饰器就变成了 celery task

    -project/app/ tasks.py:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • from celery.task import task
  • from time import sleep
  •  
  • @task()
  • def helloWorld():
  •  print 'helloWorld'
  •  sleep(10)
  •  print 'helloWorld'
  •  return 'helloCelery'
  • 这样,一个任务就创建成功了,只剩下在 view 中调用了

    -project/app view.py:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • from tasks.py import helloWorld
  •  
  • def home():
  •  
  •  helloWorld.delay()
  •  
  •  return HttpResponse('helloCelery')
  • 最后

  • ?
  • 1
  • python manage.py migrate
  • 总结

    以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对开心学习网的支持。

    原文链接:http://www.cnblogs.com/peng104/p/10580720.html

    您可能感兴趣