欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中celery的使用

 更新時(shí)間:2021年08月25日 14:41:11   作者:fivenian  
Celery是一個(gè)簡(jiǎn)單、靈活且可靠的,處理大量消息的分布式系統(tǒng),專注于實(shí)時(shí)處理的異步任務(wù)隊(duì)列,同時(shí)也支持任務(wù)調(diào)度。接下來(lái)通過(guò)本文給大家介紹Python中celery的使用詳解,感興趣的朋友一起看看吧

 Celery簡(jiǎn)介

  Celery是一個(gè)簡(jiǎn)單、靈活且可靠的,處理大量消息的分布式系統(tǒng),專注于實(shí)時(shí)處理的異步任務(wù)隊(duì)列,同時(shí)也支持任務(wù)調(diào)度。

  Celery的架構(gòu)由三部分組成,消息中間件(message broker),任務(wù)執(zhí)行單元(worker)和任務(wù)執(zhí)行結(jié)果存儲(chǔ)(task result store)組成。

  消息中間件:Celery本身不提供消息服務(wù),但是可以方便的和第三方提供的消息中間件集成。包括,RabbitMQ, Redis等等。

  任務(wù)執(zhí)行單元:Worker是Celery提供的任務(wù)執(zhí)行的單元,worker并發(fā)的運(yùn)行在分布式的系統(tǒng)節(jié)點(diǎn)中。

  任務(wù)結(jié)果存儲(chǔ):Task result store用來(lái)存儲(chǔ)Worker執(zhí)行的任務(wù)的結(jié)果,Celery支持以不同方式存儲(chǔ)任務(wù)的結(jié)果,包括AMQP, redis等。

  版本支持情況:

Celery version 4.0 runs on
        Python ❨2.7, 3.4, 3.5❩
        PyPy ❨5.4, 5.5❩
    This is the last version to support Python 2.7, and from the next version (Celery 5.x) Python 3.5 or newer is required.

    If you're running an older version of Python, you need to be running an older version of Celery:

        Python 2.6: Celery series 3.1 or earlier.
        Python 2.5: Celery series 3.0 or earlier.
        Python 2.4 was Celery series 2.2 or earlier.

    Celery is a project with minimal funding, so we don't support Microsoft Windows. Please don't open any issues related to that platform.

  Celery多用來(lái)執(zhí)行異步任務(wù),將耗時(shí)的操作交由Celery去異步執(zhí)行,比如發(fā)送郵件、短信、消息推送、音視頻處理等。還可以執(zhí)行定時(shí)任務(wù),定時(shí)執(zhí)行某件事情,比如Redis中的數(shù)據(jù)每天凌晨?jī)牲c(diǎn)保存至mysql數(shù)據(jù)庫(kù),實(shí)現(xiàn)Redis的持久化。

celery的異步任務(wù)

celery的使用

1.安裝celery

$ pip install -U celery

1)安裝相關(guān)依賴

$ pip install "celery[redis,auth,msgpack]"

序列化程序

celery[auth]

用于使用auth安全序列化程序。

celery[msgpack]

用于使用 msgpack 序列化程序。

celery[redis]

使用 Redis 作為消息傳輸或結(jié)果后端。

2.安裝redis

這里我們使用redis作為celery的broker,作為任務(wù)隊(duì)列的存儲(chǔ)和結(jié)果的存儲(chǔ)。

對(duì)于 Redis 支持,您必須安裝其他依賴項(xiàng)。您可以使用celery[redis] bundle一次性安裝 Celery 和這些依賴項(xiàng):

$ pip install -U "celery[redis]"

1)配置

配置很簡(jiǎn)單,只需配置你的 Redis 數(shù)據(jù)庫(kù)的位置:

app.conf.broker_url = 'redis://localhost:6379/0'

其中 URL 的格式為:

redis://:password@hostname:port/db_number

方案后面的所有字段都是可選的,并且將默認(rèn)為localhost 端口 6379,使用數(shù)據(jù)庫(kù) 0。

3.使用ceelry

1)首先我們可以創(chuàng)建一個(gè)celery的文件夾,然后創(chuàng)建一個(gè)tasks.py文件

celery/tasks.py

from celery import Celery

# 第一個(gè)參數(shù)就是當(dāng)前腳本的名稱,backend 任務(wù)執(zhí)行結(jié)果的存儲(chǔ)地址broker 任務(wù)隊(duì)列的存儲(chǔ)地址
app = Celery('tasks', backend='redis://127.0.0.1', broker='redis://127.0.0.1')

@app.task
def add(x, y):
    return x + y

celery/run_tasks.py

from tasks import add

result = add.delay(1, 2)
print('Is task ready: %s' % result.ready())  # False說(shuō)明任務(wù)還沒(méi)有執(zhí)行完
run_result = result.get(timeout=1)
print('task result: %s' % run_result)

print('Is task ready: %s' % result.ready())

4.啟動(dòng)celery

$ cd celry
$ celery -A tasks worker --loglevel=info

使用flower監(jiān)控celery任務(wù)的執(zhí)行情況

pip install flower

啟動(dòng)flower,指定我們的應(yīng)用,確保你的celery是啟動(dòng)的。

cd celery
celery -A tasks flower --broker=redis://@localhost:6379/0

運(yùn)行結(jié)果:

celery [celery args] flower [flower args].
[I 210825 10:54:00 command:152] Visit me at http://localhost:5555
[I 210825 10:54:00 command:159] Broker: redis://127.0.0.1:6379//
[I 210825 10:54:00 command:160] Registered tasks:

我們就可以通過(guò)5555端口看到celery異步任務(wù)的運(yùn)行情況了

![image-20210825113106220](/Users/gelong/Library/Application Support/typora-user-images/image-20210825113106220.png)

Django中使用celery

官方地址:https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

1.創(chuàng)建celery文件

根據(jù)官方文檔的說(shuō)明,我們可以直接在Django項(xiàng)目同名的應(yīng)用下創(chuàng)建celery.py文件

recruitment/recruitment/celery.py

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SEttINGS_MODULE', 'recruitment.base')  # 這里我把配置文件放到了根目錄下的settings/base.py 中

app = Celery('recruitment')

# 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()

def debug_task(self):
  print(f'Request: {self.request!r}')

然后我們需要在這個(gè)celery.py文件所在的目錄的__init__文件中添加:

from __future__ import absolute_import, unicode_literals


# This will make sure the app is always imported when/保證所有app下的任務(wù)都能導(dǎo)入進(jìn)來(lái)
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

2.添加celery配置

settings/base.py

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/1'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERYD_MAX_TASKS_PER_CHILD = 10
CELERYD_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_work.log")
CELERYBEAT_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_beat.log")

3.在別的應(yīng)用下使用celery執(zhí)行異步任務(wù) [使用celery異步發(fā)送釘釘群消息通知]

1.首先我們需要在應(yīng)用下創(chuàng)建一個(gè)tasks.py文件interview/tasks.py

from __future__ import absolute_import, unicode_literals

from celery import shared_task
from .dingtalk import send

@shared_task
def send_dingtalk_message(message):
    send(message)

interview/dingtalk.py

from dingtalkchatbot.chatbot import DingtalkChatbot

from django.conf import settings


def send(message, at_mobiles=[]):
    # 引用 settings里面配置的釘釘群消息通知的WebHook地址:
    webhook = settings.DINGTALK_WEB_HOOK

    # 初始化機(jī)器人小Y,
    xiaoY = DingtalkChatbot(webhook)

    # 方式二:勾選“加簽”選項(xiàng)時(shí)使用(v1.5以上新功能)
    # xiaoY = DingtalkChatbot(webhook, secret=secret)

    # Text消息@所有人
    xiaoY.send_text(msg=('消息通知: %s' % message), at_mobiles=at_mobiles)

interview.views.py

from interview.tasks import send_dingtalk_message

def notify_interview(modeladmin, request, queryset):
    candidates = ''
    interviewers = ''
    for obj in queryset:
        candidates = obj.userame + '' + candidates
        interviewers = obj.first_interviewer_user + '' + interviewers
    # 這里的消息發(fā)送到釘釘, 或者通過(guò) Celery 異步發(fā)送到釘釘
    send_dingtalk_message.delay('候選人 %s 進(jìn)入面試環(huán)節(jié), 親愛(ài)的面試官請(qǐng)做好面試準(zhǔn)備:%s。' % (candidates, interviewers))

4.啟動(dòng)celery服務(wù)

啟動(dòng)celery服務(wù),到我們的項(xiàng)目根目錄啟動(dòng),然后執(zhí)行

$ celery -A recruitment worker -l info

如果需要制定配置文件,如果在mac下可以執(zhí)行:

$ DJANGO_SEttINGS_MODULE=settings.base celery --app=recruitment worker --loglevel=info

啟動(dòng)flower監(jiān)控異步任務(wù)

$ celery -A recruitment flower --broker=redis://localhost:6379/0

celery定時(shí)任務(wù)

到此這篇關(guān)于Python中celery的使用的文章就介紹到這了,更多相關(guān)celery的使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python利用hook技術(shù)破解https的實(shí)例代碼

    python利用hook技術(shù)破解https的實(shí)例代碼

    python利用hook技術(shù)破解https的實(shí)例代碼,需要的朋友可以參考一下
    2013-03-03
  • python怎么刪除緩存文件

    python怎么刪除緩存文件

    在本篇文章里小編給大家整理的是一篇關(guān)于python刪除緩存文件方法,需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • jupyter notebook實(shí)現(xiàn)顯示行號(hào)

    jupyter notebook實(shí)現(xiàn)顯示行號(hào)

    這篇文章主要介紹了jupyter notebook實(shí)現(xiàn)顯示行號(hào),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • 用pywin32實(shí)現(xiàn)windows模擬鼠標(biāo)及鍵盤動(dòng)作

    用pywin32實(shí)現(xiàn)windows模擬鼠標(biāo)及鍵盤動(dòng)作

    這篇文章主要介紹了用pywin32實(shí)現(xiàn)windows模擬鼠標(biāo)及鍵盤動(dòng)作的示例,需要的朋友可以參考下
    2014-04-04
  • 淺談Python的文件類型

    淺談Python的文件類型

    下面小編就為大家?guī)?lái)一篇淺談Python的文件類型。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-05-05
  • pytorch中的model.eval()和BN層的使用

    pytorch中的model.eval()和BN層的使用

    這篇文章主要介紹了pytorch中的model.eval()和BN層的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • 利用Python腳本在Nginx和uwsgi上部署MoinMoin的教程

    利用Python腳本在Nginx和uwsgi上部署MoinMoin的教程

    這篇文章主要介紹了利用Python腳本在Nginx和uwsgi上部署MoinMoin的教程,示例基于CentOS操作系統(tǒng),需要的朋友可以參考下
    2015-05-05
  • Python pandas讀取CSV文件的注意事項(xiàng)(適合新手)

    Python pandas讀取CSV文件的注意事項(xiàng)(適合新手)

    這篇文章主要給大家介紹了關(guān)于Python pandas讀取CSV文件的注意事項(xiàng),非常適合新手,csv是我接觸的比較早的一種文件,比較好的是這種文件既能夠以電子表格的形式查看又能夠以文本的形式查看,需要的朋友可以參考下
    2021-06-06
  • 淺談Python中的常用內(nèi)置對(duì)象

    淺談Python中的常用內(nèi)置對(duì)象

    今天帶大家復(fù)習(xí)Python基礎(chǔ)知識(shí),文中對(duì)Python常用的內(nèi)置對(duì)象作了非常詳細(xì)的介紹及代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05
  • Python Matplotlib繪制條形圖的全過(guò)程

    Python Matplotlib繪制條形圖的全過(guò)程

    Python畫圖主要用到matplotlib這個(gè)庫(kù),具體來(lái)說(shuō)是pylab和pyplot這兩個(gè)子庫(kù),這兩個(gè)庫(kù)可以滿足基本的畫圖需求,下面這篇文章主要給大家介紹了關(guān)于Python Matplotlib繪制條形圖的相關(guān)資料,需要的朋友可以參考下
    2021-10-10

最新評(píng)論