本文主要是介绍web project (2nd day),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Asynchronous tasks
What is Asynchronous?
for ask the question:
there is anther question what is Synchronous?
In web project, we konw a method call ajax. ajax is a Asynchronous method. Its characteristics are: Once started, the method returns immediately and the calling place can continue to perform other functions.
So, Synchronous is completely opposite.
Synchronous, Once started, the method must waiting for returns, if not, the calling place can’t continue
if you can’t understand, here is a image to explan there different:
Need Asynchronous task in web project?
The anwser is Yes, we need.
Taking into account the user experience, when the user needs to register a mailbox, web must returns immediately, user can’t waiting 5-8s for the returns.
How to bulid and use Asynchronous task?
In Django project, we often use Celery:Distributed Task Queue
Asynchronous task consist of 3 parts
part1: Task initiation
part2: Task queue(broker)
part3: Task processing(worker)
Use Celery
First step: Build an Application
main.py
from celery import Celeryapp = Celery(name='') # taskname
app.config_from_object('proj.celeryconfig')app.autodiscover_tasks(['proj'])
proj.celeryconfig.py
BROKER_URL = 'redis://'
CELERY_RESULT_BACKEND = 'redis://'
proj.tasks
from main import app@app.task(name)
def task1():print("task1 is executing")@app.task(name)
def task2():print("task2 is executing")
....
start worker
celery -A proj worker -l info
这篇关于web project (2nd day)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!