How to use celery to send short message verification code asynchronously in Django
- 2021-11-29 07:46:04
- OfStack
Directory 1. Introduction to celery
1.1 Examples of celery Applications
1.2 Celery has the following advantages
1.3 Celery Characteristics
2. How it works 2.1 Celery plays the role of producer and consumer
3. Summary of asynchronous texting
1. Introduction of 1. celery
1.1 Examples of celery Applications
Celery is a distributed asynchronous message task queue developed based on python, through which asynchronous processing of tasks can be easily realized. If asynchronous tasks are needed in your business scenario, you can consider using celery
You want to execute a batch command on 100 machines, which may take a long time, but you don't want your program to wait for the results to return, but instead return you a task ID, you only need to hold this task id after a period of time to get the task execution results, while the task execution ing is going on, you can continue to do other things
When Celery executes a task, it needs a message middleware to receive and send task messages and store task results. Generally, rabbitMQ or Redis is used
1.2 Celery has the following advantages
Simple: 1 After familiar with the workflow of celery, configuration and use is relatively simple
High Availability: celery will automatically try to re-execute the task when the task fails or the connection is interrupted during execution
Fast: One single-process celery can handle millions of tasks per minute
Flexibility: Almost every component of celery can be extended and customized
1.3 Celery Characteristics
It is convenient to view the execution of timed tasks, such as success, current status, time spent executing tasks, etc.
Multi-process can be selected, and Eventlet and Gevent can be executed concurrently.
Celery is language independent. It provides interface support for common languages such as python.
2. How it works
2.1 The role of Celery as producer and consumer
Celery Beat: Task scheduler. The Beat process reads the contents of the configuration file and periodically sends the tasks due to be executed in the configuration to the task queue.
Celery Worker: Consumers who perform tasks usually run multiple consumers on multiple servers to improve operational efficiency.
Broker: Message broker, queue itself. Also known as message middleware. Receives task messages from task producers, queues them and distributes them sequentially to task consumers (usually message queues or databases).
Producer: Task producer. It is the task producer that calls Celery API, a function, or a decorator and generates the task and sends it to the task queue for processing.
Result Backend: Saves status information and results for query after task processing is complete.
1.2 Celery has the following advantages
1.3 Celery Characteristics
2. How it works 2.1 Celery plays the role of producer and consumer
3. Summary of asynchronous texting
1. Introduction of 1. celery
1.1 Examples of celery Applications
Celery is a distributed asynchronous message task queue developed based on python, through which asynchronous processing of tasks can be easily realized. If asynchronous tasks are needed in your business scenario, you can consider using celery
You want to execute a batch command on 100 machines, which may take a long time, but you don't want your program to wait for the results to return, but instead return you a task ID, you only need to hold this task id after a period of time to get the task execution results, while the task execution ing is going on, you can continue to do other things
When Celery executes a task, it needs a message middleware to receive and send task messages and store task results. Generally, rabbitMQ or Redis is used
1.2 Celery has the following advantages
Simple: 1 After familiar with the workflow of celery, configuration and use is relatively simple
High Availability: celery will automatically try to re-execute the task when the task fails or the connection is interrupted during execution
Fast: One single-process celery can handle millions of tasks per minute
Flexibility: Almost every component of celery can be extended and customized
1.3 Celery Characteristics
It is convenient to view the execution of timed tasks, such as success, current status, time spent executing tasks, etc.
Multi-process can be selected, and Eventlet and Gevent can be executed concurrently.
Celery is language independent. It provides interface support for common languages such as python.
2. How it works
2.1 The role of Celery as producer and consumer
Celery Beat: Task scheduler. The Beat process reads the contents of the configuration file and periodically sends the tasks due to be executed in the configuration to the task queue.
Celery Worker: Consumers who perform tasks usually run multiple consumers on multiple servers to improve operational efficiency.
Broker: Message broker, queue itself. Also known as message middleware. Receives task messages from task producers, queues them and distributes them sequentially to task consumers (usually message queues or databases).
Producer: Task producer. It is the task producer that calls Celery API, a function, or a decorator and generates the task and sends it to the task queue for processing.
Result Backend: Saves status information and results for query after task processing is complete.
3. Send text messages asynchronously
1. Create celery file in settings peer directory
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# Setting Environment Variables
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo.settings')
# Registration Celery Adj. APP
app = Celery('meiduo')
# Binding configuration file
app.config_from_object('django.conf:settings', namespace='CELERY')
# Automatically discover each app Under tasks.py Documents
app.autodiscover_tasks()
2. Configure the settings file
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/'
CELERY_RESULT_SERIALIZER = 'json'
3 Configure init file under settings peer directory
from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']
4. Create a new task. py file under utils
from celery.task import task
from .comm import send_message
# Defining Methods for Sending Messages
@task
def mail(mobile,code):
send_message(mobile,code,5)
5. Call in the interface
from utils.tasks import mail
import random
class SendMes(APIView):
# SMS authentication
def get(self,request):
# Receive the data sent by the client
imagecode = request.query_params.get('imagecode')
print(imagecode)
mobile = request.query_params.get('mobile')
print(mobile)
uuid = request.query_params.get('uuid')
print(uuid)
if not all([imagecode,mobile]):
return Response({'msg':' Not retrieved '})
# Verify the picture verification code
conn =get_redis_conn()
# redis Take the verification code in
code = conn.get(uuid)
print(code)
if code:
code = str(code,encoding='utf8')
# Comparison of picture verification codes
if imagecode.lower() == code.lower():
# Call the SMS sending interface after passing the verification
sms_code = random.randint(10000,99999)
# Focus Focus Focus! ! ! ! ! ! !
result = mail.delay(mobile,sms_code,1)
# Did you join the text message? Sent successfully
if result:
# redis Do you want to save SMS authentication in
conn.setex(mobile,60,sms_code)
# Transform the picture verification code from redis Delete in
conn.delete(uuid)
return Response({'msg':sms_code})
else:
return ({'msg':' Send failed '})
else:
return Response({'msg':' Incorrect verification code '})
return Response('ok')
6. Start the django project first and then open another terminal cd to the project directory to start the celery service
Specify concurrency number-autoscale (max, min)
celery worker -A meiduo --loglevel=info --pool=solo --autoscale=50,5