Django Send SMS Verification Code Sample Asynchronous Using celery
- 2021-11-29 07:41:07
- OfStack
celery
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 result to return, but instead you will be returned with a task ID. After a period of time, you only need to hold this task id to get the task execution result. 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, and generally uses rabbitMQ or Redis
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 automatically attempts to re-execute a task when it fails to execute or when a connection breaks during execution. Fast: One single-process celery can process millions of tasks per minute
Flexible: 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 Celery plays the role of 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. Call Celery API, function or decorator, and the task is generated and submitted to the task queue is the task producer.
Result Backend
Save status information and results for query after task processing is completed.
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 celery service specified concurrency number-autoscale (maximum, minimum)
celery worker -A meiduo --loglevel=info --pool=solo --autoscale=50,5
The above is Django using celery asynchronous send SMS verification code code example details, more about Django using celery asynchronous send SMS verification code information please pay attention to other related articles on this site!