Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Celery capacity Cloud to send CAPTCHA asynchronously in python

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to send CAPTCHA asynchronously using Celery Cloud in python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Introduction to 1.celery Asynchronous message queuing

Examples of celery applications

Celery is a distributed asynchronous message task queue developed based on python, through which you can easily implement asynchronous processing of tasks. If you need asynchronous tasks in your business scenario, you can consider using celery.

It may take a long time for you to execute a batch command on 100 machines, but you don't want your program to wait for the result to return. Instead, you will return a task ID. After a period of time, you only need to hold the task id to get the task execution result. While the task execution ing is in progress, you can continue to do other things.

Celery needs to use a message middleware to receive and send task messages and store task results when performing tasks. Generally, rabbitMQ or Redis is used.

Celery has the following advantages

Simple: after being familiar with the workflow of celery, it is relatively easy to configure and use it.

High availability: when a task fails or a connection breaks during execution, celery automatically attempts to re-execute the task

Fast: a single-process celery can handle millions of tasks per minute

Flexibility: almost every component of celery can be extended and customized

Celery characteristics

It is convenient to check the execution of scheduled tasks, such as success, current status, time spent executing tasks, etc.

Optional multi-process, Eventlet and Gevent models are executed concurrently.

Celery is language-independent. It provides interface support for common languages such as python.

two。 How it works *

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 that need to be executed when it expires 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. Accept the task messages sent by the task producer, store them in the queue and distribute them sequentially to the task consumers (usually message queues or databases).

Producer: task producer. Call Celery API, function, or decorator, and it is the task producer who generates the task and hands it over to the task queue.

Result Backend: save status information and results for query after task processing.

Mind map

3. Send text messages asynchronously

First of all, you have to install two watches to pack.

Create a celery file under the same level directory of pip install celerypip install celery-with-redis3.1.settings

If there is an error in 'namespace='CELERY''', celery can be downgraded to '4.4.7'.

From_ _ future__ import absolute_import, unicode_literalsimport osfrom celery import Celery# sets the environment variable os.environ.setdefault ('DJANGO_SETTINGS_MODULE',' md.settings') # APPapp for registering Celery = Celery ('meiduo') # binding profile app.config_from_object (' django.conf:settings') Namespace='CELERY') # automatically find tasks.py files under each app # app.autodiscover_tasks () 3.2.redis and Container Cloud configuration # get redis connection def getRedis (): from django_redis import get_redis_connection conn = get_redis_connection () return conn# send text messages to Lianlian Cloud official website to find your own information from ronglian_sms_sdk import SmsSDKaccId = 'ACCOUNT SID (main account ID)' accToken = 'AUTH TOKEN ( Account authorization token) 'appId =' AppID (default) 'import jsondef send_message (mobile Code,time): sdk = SmsSDK (accId, accToken, appId) tid ='1' datas = (code,time) resp = sdk.sendMessage (tid, mobile, datas) result = json.loads (resp) if result ['statusCode'] = =' 0000000: return 1 return 23.3. 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.4. Configure the init file from _ future__ import absolute_import under the settings sibling directory, unicode_literalsfrom. Celery import app as celery_app__all__ = [' celery_app'] 3.5. Create a new task.py file under utils # where asynchronous tasks are written. Comm import send_message# defines the method for sending mobile phone numbers @ taskdef mail (mobile,code,time): send_message (mobile,code,time) 3.6. Call in the interface

If you use the redis database, you have to open the database first

From utils.task import send_messagefrom utils.comm import getRedisimport randomclass SendMes (APIView): # SMS verification def get (self Request): # receiving 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':' did not get'}) # verify the picture verification code conn = getRedis () # redis take the verification code code = conn.get (uuid) print (code) if code: code = str (code Encoding='utf8') # Picture verification code comparison if imagecode.lower () = code.lower (): # call the SMS sending API sms_code = random.randint (10000J 99999) # reference send_message result = send_message (mobile,sms_code) in the comm file 1) # do you want to add an SMS message? send it successfully? if result: # do you want to save SMS verification in redis? conn.setex (mobile,60) Sms_code) # remove the image verification code from redis conn.delete (uuid) return Response ({'msg':sms_code}) else: return ({' msg':' failed'}) else: return Response ( {'msg':' verification code is incorrect'}) return Response ('ok') 3.7. Start the django project first

Then open another terminal cd to start the celery service under the project directory

Specify the number of concurrency-autoscale (maximum, minimum)

The file name of celery worker-A project-- loglevel=info-- pool=solo-- autoscale=50,5urn Response ('ok') ~ ~ # 3.7. First start the django project and then open another terminal cd to start the celery service under the project directory to specify the number of concurrency-autoscale (most, minimum) ````pyhoncelery worker-A project file name-loglevel=info-- pool=solo-- autoscale=50,5 thank you for reading! This is the end of the article on "how to send CAPTCHA asynchronously in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report