<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title><![CDATA[运维进行时]]></title> 
<link>https://blog.liuts.com/index.php</link> 
<description><![CDATA[互联网运维与架构]]></description> 
<language>zh-cn</language> 
<copyright><![CDATA[运维进行时]]></copyright>
<item>
<link>https://blog.liuts.com/post/248/</link>
<title><![CDATA[基于Django与Celery实现异步对列任务]]></title> 
<author>刘天斯 &lt;liutiansi@gmail.com&gt;</author>
<category><![CDATA[Python]]></category>
<pubDate>Tue, 18 Aug 2015 11:42:06 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/</guid> 
<description>
<![CDATA[ 
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在运营系统中经常用到异步方式来处理我们的任务，比如将业务上线流程串成任务再写入队列，通过后台作业节点去调度执行。比较典型的案例为腾讯的蓝鲸、织云、云智慧等平台。本译文结合Django+Celery+Redis实现一个定期从Flickr 获取图片并展示的简单案例，方便大家理解实现异步对列任务的过程。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;刚接触django的时候，我经历过的最让人沮丧的事情是需要定期运行一段代码。我写了一个需要每天上午12点执行一个动作的不错的函数。很简单是不是？错了。事实证明，这对我来说是一个巨大的困难点，因为，那时我使用Cpane类型的虚拟主机管理系统，它能专门提供一个很友好，很方便的图形用户界面来设置cron作业。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 经过反复研究，我发现了一个很好的解决方案 - Celery，一个用于在后台运行任务的强大的异步作业队列。但是，这也导致了其它的问题，因为我无法找到一系列简单的指令将celery集成到Django项目中。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 当然，我最终还是设法成功搞定了它 - 这正是本文将介绍的内容：如何将celery集成到一个Django项目，创建周期性任务。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 该项目利用Python3.4，Django的1.8.2，celery3.1.18和Redis3.0.2.<br/><br/><strong>一、概述</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 由于大篇幅的文字，为了您的方便，请参阅下表中的每一步的简要信息，并获取相关的代码。<br/>步骤&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;概要&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Git标签<br/>样板&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;样板下载&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v1" target="_blank">V1</a><br/>建立&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;集成Celery和Django&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v2" target="_blank">V2</a><br/>Celery任务&nbsp;&nbsp;&nbsp;&nbsp;添加基本的Celery任务&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v3" target="_blank">V3</a><br/>周期性任务&nbsp;&nbsp;&nbsp;&nbsp;添加周期性任务&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v4" target="_blank">V4</a><br/>本地运行&nbsp;&nbsp;&nbsp;&nbsp;本地运行我们的应用程序&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v5" target="_blank">V5</a><br/>远程运行&nbsp;&nbsp;&nbsp;&nbsp;远程运行我们的应用程序&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/realpython/Picha/releases/tag/v5" target="_blank">V5</a><br/><br/><strong>二、什么是Celery</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; “Celery是一个异步任务队列/基于分布式消息传递的作业队列。它侧重于实时操作，但对调度的支持也很好。”本文，我们将重点讲解周期性执行任务的调度特点。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 为什么这一点有用呢？<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;•回想一下你不得不在将来运行某一特定任务的经历。也许你需要每隔一小时访问一个API。或者，也许你需要在这一天结束时发送一批电子邮件。不论任务大小，Celery都可以使得调度周期性任务变的很容易。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;•你永远不希望终端用户等待那些不必要的页面加载或动作执行完成。如果你的应用程序工作流的一部分是一个需要很长时间的程序，当资源可用时，你就可以使用Celery在后台执行这段程序，从而使你的应用程序可以继续响应客户端的请求。这样可以使任务在应用程序的环境之外运行。<br/><br/><strong>三、构建项目</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在深入了解Celery之前，先从Github库中获取开始项目。确保激活一个虚拟的环境，安装必要的软件，并运行迁移。然后启动服务器，通过你的浏览器导航到http://localhost:8000/。你应当能看到‘恭喜你的第一个Django页面’。完成后，关闭服务器。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 接下来，我们开始安装celery。<br/><textarea name="code" class="c" rows="15" cols="100">
$ pip install celery==3.1.18
$ pip freeze > requirements.txt
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 现在，我们通过简单的三步将celery集成到django项目中。<br/><strong>步骤一：创建celery.py</strong><br/>在“picha“目录下，创建celery.py，代码如下：<br/><textarea name="code" class="python" rows="15" cols="100">
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'picha.settings')
app = Celery('picha')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True)
def debug_task(self):
&nbsp;&nbsp;&nbsp;&nbsp;print('Request: &#123;0!r&#125;'.format(self.request))
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 请注意代码中的注释。<br/><strong>步骤二：引入celery应用</strong><br/>为了确保在django启动时加载了celery应用，在settings.py旁边新建__init__.py，并添加以下代码到__init__.py中。<br/><textarea name="code" class="python" rows="15" cols="100">
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
</textarea><br/>完成以上步骤后，你的项目目录应该是这样的：<br/><textarea name="code" class="c" rows="15" cols="100">
├── manage.py
├── picha
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── celery.py
│&nbsp;&nbsp; ├── settings.py
│&nbsp;&nbsp; ├── urls.py
│&nbsp;&nbsp; └── wsgi.py
└── requirements.txt
</textarea><br/><strong>步骤三：安装 Redis作为Celery的“中间件”</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;Celery使用中间件在django项目与celery监控者之间传递消息。在本教程中，我们使用redis作为消息中间代理。<br/>首先，从官方下载页面或通过brew（BREW安装Redis）安装Redis，然后打开你的终端上，在一个新的终端窗口，启动服务器：<br/><textarea name="code" class="c" rows="15" cols="100">
$ redis-server
</textarea><br/>你可以通过在终端中输入如下命令测试Redis是否正常工作。<br/><textarea name="code" class="c" rows="15" cols="100">
$ redis-cli ping
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Redis应该回复PONG - 试试吧！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 一旦Redis正常启动了，把下面的代码添加到你的settings.py文件中：<br/><textarea name="code" class="python" rows="15" cols="100">
# CELERY STUFF
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Africa/Nairobi'
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 你还需要添加Redis的作为Django项目的依赖：<br/><textarea name="code" class="c" rows="15" cols="100">
$ pip install redis==2.10.3
$ pip freeze > requirements.txt
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 就是这样了！你现在应该能够在Django中使用Celery。有关设置Celery与Django的更多信息，请查看官方Celery文档。<br/>在继续下面步骤之前，让我们进行一些完整性检查，以确保一切都是正常的。<br/>测试Celery worker已准备好接收任务：<br/><textarea name="code" class="c" rows="15" cols="100">
$ celery -A picha worker -l info
...
[2015-07-07 14:07:07,398: INFO/MainProcess] Connected to redis://localhost:6379//
[2015-07-07 14:07:07,410: INFO/MainProcess] mingle: searching for neighbors
[2015-07-07 14:07:08,419: INFO/MainProcess] mingle: all alone
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 使用CTRL-C杀死该段程序。现在，测试Celery任务调度程序是否已经准备好：<br/><textarea name="code" class="c" rows="15" cols="100">
$ celery -A picha beat -l info
...
[2015-07-07 14:08:23,054: INFO/MainProcess] beat: Starting...
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在上述完成时再次终止该进程。<br/><br/><strong>1、Celery任务</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Celery利用celery调用的常规Python函数作为任务。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例如，让我们把这个基本函数变为celery的任务：<br/><textarea name="code" class="python" rows="15" cols="100">
def add(x, y):
&nbsp;&nbsp;&nbsp;&nbsp;return x + y
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 首先，添加一个装饰器。<br/><textarea name="code" class="python" rows="15" cols="100">
from celery.decorators import task

@task(name="sum_two_numbers")
def add(x, y):
&nbsp;&nbsp;&nbsp;&nbsp;return x + y
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 然后你可以通过以下方式利用celery异步运行该任务：<br/><textarea name="code" class="python" rows="15" cols="100">
add.delay(7, 8)
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 很简单，对不对？<br/>所以，这对于解决类似你要加载一个网页，而不需要用户等待一些后台程序的完成这些类型的任务来说是非常完美的。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;让我们来看一个例子...<br/>让我们再回到Django项目的版本3，它包括一个接受来自用户的反馈的应用程序，人们形象地称之为反馈：<br/><textarea name="code" class="c" rows="15" cols="100">
├── feedback
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── admin.py
│&nbsp;&nbsp; ├── emails.py
│&nbsp;&nbsp; ├── forms.py
│&nbsp;&nbsp; ├── models.py
│&nbsp;&nbsp; ├── tests.py
│&nbsp;&nbsp; └── views.py
├── manage.py
├── picha
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── celery.py
│&nbsp;&nbsp; ├── settings.py
│&nbsp;&nbsp; ├── urls.py
│&nbsp;&nbsp; └── wsgi.py
├── requirements.txt
└── templates
&nbsp;&nbsp;&nbsp;&nbsp;├── base.html
&nbsp;&nbsp;&nbsp;&nbsp;└── feedback
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── contact.html
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── email
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── feedback_email_body.txt
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── feedback_email_subject.txt
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 安装新的必要软件，启动应用程序，并导航到http://localhost:8000/feedback/。你应该看到如下结果：<br/><a href="https://blog.liuts.com/attachment.php?fid=376" target="_blank"><img src="https://blog.liuts.com/attachment.php?fid=376" class="insertimage" alt="点击在新窗口中浏览此图片" title="点击在新窗口中浏览此图片" border="0"/></a><br/>让我们连接celery任务。<br/><br/><strong>2、添加任务</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 基本上，用户提交反馈表后，我们希望让他继续以他舒服的方式往下进行，而我们在后台进行处理反馈，发送电子邮件等等。<br/>要做到这一点，首先添加一个叫tasks.py的文件到“feedback”目录：<br/><textarea name="code" class="python" rows="15" cols="100">
from celery.decorators import task
from celery.utils.log import get_task_logger

from feedback.emails import send_feedback_email

logger = get_task_logger(__name__)


@task(name="send_feedback_email_task")
def send_feedback_email_task(email, message):
&nbsp;&nbsp;&nbsp;&nbsp;"""sends an email when feedback form is filled successfully"""
&nbsp;&nbsp;&nbsp;&nbsp;logger.info("Sent feedback email")
&nbsp;&nbsp;&nbsp;&nbsp;return send_feedback_email(email, message)
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 然后按照如下内容更新forms.py：<br/><textarea name="code" class="python" rows="15" cols="100">
from django import forms
from feedback.tasks import send_feedback_email_task


class FeedbackForm(forms.Form):
&nbsp;&nbsp;&nbsp;&nbsp;email = forms.EmailField(label="Email Address")
&nbsp;&nbsp;&nbsp;&nbsp;message = forms.CharField(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;label="Message", widget=forms.Textarea(attrs=&#123;'rows': 5&#125;))
&nbsp;&nbsp;&nbsp;&nbsp;honeypot = forms.CharField(widget=forms.HiddenInput(), required=False)

&nbsp;&nbsp;&nbsp;&nbsp;def send_email(self):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# try to trick spammers by checking whether the honeypot field is
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# filled in; not super complicated/effective but it works
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if self.cleaned_data['honeypot']:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return False
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send_feedback_email_task.delay(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.cleaned_data['email'], self.cleaned_data['message'])
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 大体上，send_feedback_email_task.delay(email, message)的函数过程，并发送反馈电子邮件等都是在用户继续使用该网站的同时作为后台进程运行。<br/>注：在views.py中的success_url被设置为将用户重定向到/ 目录，这个目录还不存在。我们会在下一节设置这个终点启动。<br/><br/><strong>3、周期任务</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 通常情况下，你经常需要安排一个任务在特定的时间运行 - 例如，一个web scraper 可能需要每天都运行。这样的任务，被称为周期性任务，很容易建立利用celery启动。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; celery使用“celery beat”来安排定期任务。celery beat定期运行任务，然后由celery worker执行任务。<br/>例如，下面的任务计划每15分钟运行一次：<br/><textarea name="code" class="python" rows="15" cols="100">
from celery.task.schedules import crontab
from celery.decorators import periodic_task


@periodic_task(run_every=(crontab(minute='*/15')), name="some_task", ignore_result=True)
def some_task():
&nbsp;&nbsp;&nbsp;&nbsp;# do something
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 让我们通过往Django项目中添加功能来看一个更强大的例子。<br/>回到Django项目版本4，它包括另一个新的应用程序，叫做photos，这个应用程序使用 Flickr API获取新照片用来显示在网站：<br/><textarea name="code" class="c" rows="15" cols="100">
├── feedback
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── admin.py
│&nbsp;&nbsp; ├── emails.py
│&nbsp;&nbsp; ├── forms.py
│&nbsp;&nbsp; ├── models.py
│&nbsp;&nbsp; ├── tasks.py
│&nbsp;&nbsp; ├── tests.py
│&nbsp;&nbsp; └── views.py
├── manage.py
├── photos
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── admin.py
│&nbsp;&nbsp; ├── models.py
│&nbsp;&nbsp; ├── settings.py
│&nbsp;&nbsp; ├── tests.py
│&nbsp;&nbsp; ├── utils.py
│&nbsp;&nbsp; └── views.py
├── picha
│&nbsp;&nbsp; ├── __init__.py
│&nbsp;&nbsp; ├── celery.py
│&nbsp;&nbsp; ├── settings.py
│&nbsp;&nbsp; ├── urls.py
│&nbsp;&nbsp; └── wsgi.py
├── requirements.txt
└── templates
&nbsp;&nbsp;&nbsp;&nbsp;├── base.html
&nbsp;&nbsp;&nbsp;&nbsp;├── feedback
&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp; ├── contact.html
&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp; └── email
&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ├── feedback_email_body.txt
&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; └── feedback_email_subject.txt
&nbsp;&nbsp;&nbsp;&nbsp;└── photos
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── photo_list.html
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 安装新的必要软件，运行迁移，然后启动服务器，以确保一切都是好的。重新测试反馈表。这次，它应该重定向好了。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 下一步是什么？<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 既然我们需要周期性的调用Flickr API，以获取更多的照片添加到我们的网站，我们可以添加一个celery任务。<br/><br/><strong>4、添加任务</strong><br/>往photos应用中添加一个tasks.py。<br/><textarea name="code" class="python" rows="15" cols="100">
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery.utils.log import get_task_logger

from photos.utils import save_latest_flickr_image

logger = get_task_logger(__name__)


@periodic_task(
&nbsp;&nbsp;&nbsp;&nbsp;run_every=(crontab(minute='*/15')),
&nbsp;&nbsp;&nbsp;&nbsp;name="task_save_latest_flickr_image",
&nbsp;&nbsp;&nbsp;&nbsp;ignore_result=True
)
def task_save_latest_flickr_image():
&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;Saves latest image from Flickr
&nbsp;&nbsp;&nbsp;&nbsp;"""
&nbsp;&nbsp;&nbsp;&nbsp;save_latest_flickr_image()
&nbsp;&nbsp;&nbsp;&nbsp;logger.info("Saved image from Flickr")
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在这里，我们通过在一个task中包装这个函数，来实现每15分钟运行一次save_latest_flickr_image()函数。该@periodic_task装饰器抽象出代码来运行celery任务，使得tasks.py干净，易于阅读！<br/><br/><strong>5、本地运行</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 准备开始运行了？<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在Django应用程序和Redis运行的前提下，打开两个新的终端窗口/标签。在每一个新的窗口中，导航到你的项目目录，激活你的虚拟环境，然后运行下面的命令（每个窗口一个）：<br/><textarea name="code" class="c" rows="15" cols="100">
$ celery -A picha worker -l info
$ celery -A picha beat -l info
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 当你访问http://127.0.0.1:8000/ 网址的时候，你现在应该能看到一个图片。我们的应用程序每15分钟从Flickr 获取一张图片。<br/><a href="https://blog.liuts.com/attachment.php?fid=377" target="_blank"><img src="https://blog.liuts.com/attachment.php?fid=377" class="insertimage" alt="点击在新窗口中浏览此图片" title="点击在新窗口中浏览此图片" border="0"/></a><br/><a href="https://blog.liuts.com/attachment.php?fid=378" target="_blank"><img src="https://blog.liuts.com/attachment.php?fid=378" class="insertimage" alt="点击在新窗口中浏览此图片" title="点击在新窗口中浏览此图片" border="0"/></a><br/>通过photos/tasks.py查看代码。点击“Feedback”按钮发送一些反馈意见：<br/><a href="https://blog.liuts.com/attachment.php?fid=379" target="_blank"><img src="https://blog.liuts.com/attachment.php?fid=379" class="insertimage" alt="点击在新窗口中浏览此图片" title="点击在新窗口中浏览此图片" border="0"/></a><br/><a href="https://blog.liuts.com/attachment.php?fid=380" target="_blank"><img src="https://blog.liuts.com/attachment.php?fid=380" class="insertimage" alt="点击在新窗口中浏览此图片" title="点击在新窗口中浏览此图片" border="0"/></a><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 以上是通过celery任务运行的。更多的请查看<span style="color: #FF4500;">feedback/tasks.py</span>。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 就这样，你成功的启动并运行了 Picha项目！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 当你本地开发Django项目时，这是一个很好的测试，但是当你需要部署到生产环境- 就像 DigitalOcean时，就不那么合适了。为此，建议你通过使用Supervisor在后台作为一个守护进程运行celery worker和调度器。<br/><br/><strong>6、远程运行</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 安装很简单。从版本库中获取版本5（如果你还没有的话）。然后，SSH到远程服务器，并运行：<br/><textarea name="code" class="c" rows="15" cols="100">
$ sudo apt-get install supervisor
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 然后，通过在远程服务器上“/etc/supervisor/conf.d/” 目录下添加配置文件来告知Supervisor celery的workers。在我们的例子中，我们需要两个这样的配置文件 - 一个用于Celery worker，一个是Celery scheduler。<br/>在本地，在项目的根目录下创建一个“supervisor”的文件夹，然后添加下面的文件。<br/><span style="color: #8B0000;">Celery Worker: picha_celery.conf</span><br/><textarea name="code" class="python" rows="15" cols="100">
; ==================================
;&nbsp;&nbsp;celery worker supervisor example
; ==================================

; the name of your supervisord program
[program:pichacelery]

; Set full path to celery program if using virtualenv
command=/home/mosh/.virtualenvs/picha/bin/celery worker -A picha --loglevel=INFO

; The directory to your Django project
directory=/home/mosh/sites/picha

; If supervisord is run as the root user, switch users to this UNIX user account
; before doing any processing.
user=mosh

; Supervisor will start as many instances of this program as named by numprocs
numprocs=1

; Put process stdout output in this file
stdout_logfile=/var/log/celery/picha_worker.log

; Put process stderr output in this file
stderr_logfile=/var/log/celery/picha_worker.log

; If true, this program will start automatically when supervisord is started
autostart=true

; May be one of false, unexpected, or true. If false, the process will never
; be autorestarted. If unexpected, the process will be restart when the program
; exits with an exit code that is not one of the exit codes associated with this
; process’ configuration (see exitcodes). If true, the process will be
; unconditionally restarted when it exits, without regard to its exit code.
autorestart=true

; The total number of seconds which the program needs to stay running after
; a startup to consider the start successful.
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

; When resorting to send SIGKILL to the program to terminate it
; send SIGKILL to its whole process group instead,
; taking care of its children as well.
killasgroup=true

; if your broker is supervised, set its priority higher
; so it starts first
priority=998
</textarea><br/><span style="color: #8B0000;">Celery Scheduler: picha_celerybeat.conf</span><br/><textarea name="code" class="python" rows="15" cols="100">
; ================================
;&nbsp;&nbsp;celery beat supervisor example
; ================================

; the name of your supervisord program
[program:pichacelerybeat]

; Set full path to celery program if using virtualenv
command=/home/mosh/.virtualenvs/picha/bin/celerybeat -A picha --loglevel=INFO

; The directory to your Django project
directory=/home/mosh/sites/picha

; If supervisord is run as the root user, switch users to this UNIX user account
; before doing any processing.
user=mosh

; Supervisor will start as many instances of this program as named by numprocs
numprocs=1

; Put process stdout output in this file
stdout_logfile=/var/log/celery/picha_beat.log

; Put process stderr output in this file
stderr_logfile=/var/log/celery/picha_beat.log

; If true, this program will start automatically when supervisord is started
autostart=true

; May be one of false, unexpected, or true. If false, the process will never
; be autorestarted. If unexpected, the process will be restart when the program
; exits with an exit code that is not one of the exit codes associated with this
; process’ configuration (see exitcodes). If true, the process will be
; unconditionally restarted when it exits, without regard to its exit code.
autorestart=true

; The total number of seconds which the program needs to stay running after
; a startup to consider the start successful.
startsecs=10

; if your broker is supervised, set its priority higher
; so it starts first
priority=999
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 注：确保更新这些文件的路径，以匹配你的远程服务器的文件系统。<br/>基本上，这些supervisor 配置文件告诉supervisord如何运行并管理我们的'programs'（因为它们是由supervisord调用）。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 在上面的例子中，我们已经创建了两个名为“pichacelery”和“pichacelerybeat”的supervisord程序。<br/>现在，只需将这些文件拷贝到远程服务器的/etc/supervisor/conf.d/目录下。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 我们还需要在远程服务器上创建上面脚本中提到的日志文件：<br/><textarea name="code" class="c" rows="15" cols="100">
$ touch /var/log/celery/picha_worker.log
$ touch /var/log/celery/picha_beat.log
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 最后，运行以下命令，使 Supervisor 知道它所管理的程序的存在 - 例如，pichacelery和pichacelerybeat：<br/><textarea name="code" class="c" rows="15" cols="100">
$ sudo supervisorctl reread
$ sudo supervisorctl update
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 运行以下命令停止，启动，和/或检查pichacelery程序的状态：<br/><textarea name="code" class="c" rows="15" cols="100">
$ sudo supervisorctl stop pichacelery
$ sudo supervisorctl start pichacelery
$ sudo supervisorctl status pichacelery
</textarea><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 你可以通过阅读官方文档获取Supervisor的更多信息。<br/><br/><strong>7、最后提示</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. 千万不要传递Django模型对象到celery任务。为了避免模型对象在传递给celery任务之前已经改变了，传递celery的主键给celery。然后，在运行之前使用主键从数据库中获取对象。<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. 默认celery调度会在本地创建一些文件存储它的调度表。这些文件是“celerybeat-schedule.db”和“celerybeat.pid”。如果你在使用版本控制系统，比如Git（你应该使用！），请忽略这个文件，不要将它们添加到你的代码库中，因为它们是为本地运行的进程服务的。<br/><br/><strong>8、下一步</strong><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 以上就是将celery集成到一个django项目的基本介绍。<br/>想要更多？<br/>1. 深入研究官方celery用户指南，以了解更多信息。<br/>2. 创建一个Fabfile来设置Supervisor和配置文件。确保添加命令到reread和 update Supervisor。<br/>3. 从repo中获取这个项目，并打开一个Pull 请求来添加一个新的celery任务。<br/>编码快乐！<br/><br/>原文：<a href="https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/" target="_blank">https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/</a><br/>Tags - <a href="https://blog.liuts.com/tags/django/" rel="tag">django</a> , <a href="https://blog.liuts.com/tags/celery/" rel="tag">celery</a> , <a href="https://blog.liuts.com/tags/%25E5%25BC%2582%25E6%25AD%25A5/" rel="tag">异步</a> , <a href="https://blog.liuts.com/tags/%25E4%25BB%25BB%25E5%258A%25A1/" rel="tag">任务</a> , <a href="https://blog.liuts.com/tags/%25E5%25AF%25B9%25E5%2588%2597/" rel="tag">对列</a>
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post/248/#blogcomment2611</link>
<title><![CDATA[[评论] 基于Django与Celery实现异步对列任务]]></title> 
<author>MorningSong &lt;user@domain.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Thu, 20 Aug 2015 08:53:36 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/#blogcomment2611</guid> 
<description>
<![CDATA[ 
	好文！前段时间刚搞定这块，案例是调用python多进程检测任务。几点建议：1、与django结合可以使用django-celery；2、celery 3.1.x版本与多进程结合要注意pool daemon = True的问题；3、crontab或intervals可以考虑直接操作数据表，@periodic_task(run_every=(crontab(minute=&#039;*/15&#039;)), name=&quot;some_task&quot;, ignore_result=True) 这种硬编码比较不够灵活。
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post/248/#blogcomment2623</link>
<title><![CDATA[[评论] 基于Django与Celery实现异步对列任务]]></title> 
<author>xyz &lt;fdsere@126.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Wed, 04 Nov 2015 01:38:39 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/#blogcomment2623</guid> 
<description>
<![CDATA[ 
	好文哦，赞一个！
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post/248/#blogcomment2634</link>
<title><![CDATA[[评论] 基于Django与Celery实现异步对列任务]]></title> 
<author>shine_forever &lt;shine_forever@yeah.net&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Wed, 06 Apr 2016 06:43:26 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/#blogcomment2634</guid> 
<description>
<![CDATA[ 
	利用celery可以实现不同的节点实现不同的调度任务吗？！请问有没相关的资料分享下！
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post/248/#blogcomment2643</link>
<title><![CDATA[[评论] 基于Django与Celery实现异步对列任务]]></title> 
<author>xiong &lt;admin@bear2.cn&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Fri, 20 May 2016 11:55:40 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/#blogcomment2643</guid> 
<description>
<![CDATA[ 
	赞
]]>
</description>
</item><item>
<link>https://blog.liuts.com/post/248/#blogcomment2652</link>
<title><![CDATA[[评论] 基于Django与Celery实现异步对列任务]]></title> 
<author>阿图 &lt;ccc@12.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Mon, 22 Aug 2016 02:11:33 +0000</pubDate> 
<guid>https://blog.liuts.com/post/248/#blogcomment2652</guid> 
<description>
<![CDATA[ 
	每篇都是雄文哈
]]>
</description>
</item>
</channel>
</rss>