当前位置:网站首页>Asynchronous data SMS verification code
Asynchronous data SMS verification code
2022-07-19 05:04:00 【du fei】
1.Celery Simple use
pip install celery==4.4.7
pip install eventlet==0.26.1
celery, Distributed asynchronous task queue
eventlet, Concurrent Network Library gevent Process library
- Create a laufing.py Write code in the file
# Instantiate objects
from celery import Celery
# The first parameter worker name
# broker agent , Message middleware
# "myworker", broker="redis://: password ( No password, no need to write )@localhost:6379/ Select Library "
app = Celery("myworker", broker="redis://:[email protected]:6379/4")
# It's fine too app.conf.broker_url = "xxxx"
# Create a task function
@app.task
def task1():
print(" Executing task ...")
#window
# Port input command
celery -A laufing worker -l info -P eventlet
ipython Simulate sending tasks : stay laufing.py Open a cmd Command line .
2. Celery Store task results
Create a laufing.py file , And create worker
from celery import Celery
app = Celery("worker2", broker="redis://:[email protected]:6379/4", backend="redis://:[email protected]:6379/5")
@app.task
def task1(a, b):
print(" Simple summation ")
return a + b
@app.task
def task2(a, b):
print("2-s After the sum ")
time.sleep(20)
return a + b
The front desk starts worker
#window
celery -A laufing worker -l info -P eventlet
Send task , And get the results
ipython The test is as follows :
from laufing import task1, task2
r1 = task1.delay(3, 5) # Send task
r1.result
r2 = task2.delay(4, 7) # Send task , And immediately execute the next line , It won't block
r2.result # worker To execute task, Only after returning the results can you get
2. celery Send SMS asynchronously
- stay django In the main application of the project , establish config.py Write code in the file
broker_url = 'redis://:@127.0.0.1:6379/2'
result_backend = 'redis://:@127.0.0.1:6379/3'
- Under the main application, create a celery.py File write code
from celery import Celery
from django.conf import settings
import os
# Set the environment variable
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'num5.settings')
# Instantiation celery object
app = Celery('cc')
# Through the configuration file , To configure
app.config_from_object('num5.config')
# Give Way app Auto discovery task function
app.autodiscover_tasks(settings.INSTALLED_APPS)
- Create a tasks.py File encapsulation function
from num5.celery import app
from ronglian_sms_sdk import SmsSDK
import json
accId = '8aaf07088185853e01818a78d71c0195' # Master account ID
accToken = '982f2e6dd6a54e6f83d014bc22ac7206' # Account authorization token
appId = '8aaf07088185853e01818a78d80e019c' # Default
# Create your tests here.
# Define the function of sending SMS
@app.task
def sms_message(sms_code, mobile, expire=5):
""" :param sms_code: The verification code to be sent :param mobile: Mobile number sent :param expire: Expiration time :return: """
# Instantiation sdk object
sdk = SmsSDK(accId=accId, accToken=accToken, appId=appId)
# Prepare the data
tid = '1'
datas = ("%s" % sms_code, "%s" % expire)
# Send a text message
res = sdk.sendMessage(tid=tid, mobile=mobile, datas=datas)
# analysis json character string
data = json.loads(res)
print(' Data responded by Ronglian cloud :', data)
# if data.get('statusCode') == '000000':
# return True
#
# return False
return data
- Go to views Write class view in
from users.tasks import sms_message
import random, re
# Verification Code
class SmsCodeAPIView(APIView):
# Send SMS verification code
def get(self, request):
mobile = request.query_params.get('mobile')
sms_code = random.randint(1000, 9999)
# Judge the cell phone number
ser = re.findall(r'^1[3-9][0-9]{9}$', mobile)
if not ser:
return Response({
'code': 400, 'msg': ' Please input the correct mobile number '})
# Send a text message
sms_message.delay(sms_code, mobile)
# Here, you can directly execute the next command without waiting for the text message to be sent
r = redis.Redis(host='127.0.0.1', port=6379)
r.set(mobile, sms_code, ex=(60 * 60 * 2))
return Response({
'code': 200, 'msg': ' Sent, please check '})
- Running Terminal , Run the command on a new terminal
celery -A num5 worker -l info -P eventlet

边栏推荐
猜你喜欢
随机推荐
Construction and application of knowledge map de (VI): storage, service and quality of knowledge map
ES文档操作
mysql主从架构和读写分离、以及高可用架构
Database learning notes (I) retrieval data
Flask的使用
微众对接机制备忘
Mysql database table a data synchronization to table b
Freshman task-5
String字符串根据符号进行特殊截取处理
三种高并发方式实现i++
POC——DVWA‘s File Inclusion
NPM installation tutorial
邮箱发送邮件(包含附件,网易、QQ)
Cve-2020-10199 recurrence of nexus repository manager3 remote command execution vulnerability
解决[email protected]: `node install.js` 的问题
TopicExchange交换机简单使用。
POC——DVWA‘s XSS Reflected
ModerlArts第一次培训笔记
Tidb performance optimization overview
Harmonyos second training notes









