Django project practice ---- realize the logic of sending SMS verification code and verify whether the picture verification code is correct (verification code 2 ends)

To realize the function of sending SMS verification code, we need to use a third-party library. Here we use Ronglian cloud

Use Ronglian cloud to build applications
  • Build a new application
  • Just check the SMS verification code
  • After the creation is successful, click application management to view it

    Account ID and account Token

    Application ID
Download Interface

Ronglian cloud can use the pip download interface
Ronglian cloud interface document, view and download
https://doc.yuntongxun.com/p/5f029ae7a80948a1006e776e

pip install ronglian_sms_sdk
Test SMS verification code interface
import json

from ronglian_sms_sdk import SmsSDK

# Put the account id, account token and application id of your account
accId = '8a216da878005a******d30a4ed04f10'
accToken = '8cae05731fe******36e6090344732ac'
appId = '8a216da878005a******d30a4fcb4f16'


class SmsUtil:
	# Create a single instance to avoid sending a short message verification code and creating an object
    def __new__(cls, *args, **kwargs):
        if not hasattr(SmsUtil, '_instance'):
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.sms_sdk = SmsSDK(accId, accToken, appId)
        return cls._instance

    def send_message(self, tid, mobile, datas):
        # sdk = SmsSDK(accId, accToken, appId)

        resp = self.sms_sdk.sendMessage(tid, mobile, datas)
        resp_dict = json.loads(resp)
        if resp_dict.get('statusCode') == '000000':
            print("SMS sent successfully")
            return 0

        else:
            print('Sending SMS failed')
            return 1


if __name__ == '__main__':
	# send_ The message method sends a short message. Parameter 1 is the template, parameter 2 is the mobile phone number, and parameter 3 is the tuple verification code and effective time
	# Call this method to send text messages
    SmsUtil().send_message('1', '198****0137', ('456853', '2'))

In view process

1. Obtain the parameters from the front end, the picture verification code entered by the user, the corresponding uuid and the user's mobile phone number.
2. Judge whether the parameter is missing.
3. According to the uuid sent from the front end, go to the redis database to find and extract the content of the picture verification code.
3.1 if it is not taken out according to uuid, it means that the verification code has expired.
3.2 the retrieved data from redis database is binary data. If it is retrieved, it should be decoded by decode().
3.3 if you take out the verification code content, delete the verification code content in redis to save memory space.
4. The content retrieved by redis is compared with the content entered by the user. If it is different, it indicates that the verification code is entered incorrectly.
5. If it is the same, a 6-digit verification code will be generated and stored in the redis database to send SMS verification code
sms_code = '%06d' % randint(0, 999999)
%d is a number,% 6d is a 6-digit number, and the empty part of% 06d is filled with 0

6. Send SMS

code:

Because objects are generated every time the redis database is connected, using pipes saves time
#Create redis pipeline to save time
pl = redis_cli.pipeline()
#Save frequently verified variables and SMS verification codes to redis database
pl.setex('send_flag_%s' % mobile, 180, 1)
pl.setex('sms_%s' % mobile, 180, sms_code)
#Perform operations
pl.execute()
Put all the operations into the pipeline to save time

be careful:
Because users frequently send text messages, when sending text messages, a variable is regularly created and stored in the redis database. If the mobile phone number used for registration sends another text message verification code within 180 seconds, the operation will be returned frequently

class SmsCodeView(View):
    def get(self, request, mobile):
        # Get the data from the front end, the picture verification code input by the user and the corresponding uuid
        get_dict = request.GET
        image_code = get_dict.get('image_code')
        uuid = get_dict.get('image_code_id')
        # Returns if the parameter is missing
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': 'Incomplete parameters'})

        # Connect to redis
        redis_cli = get_redis_connection('code')
        # Get the correct picture verification code according to uuid
        redis_image_code = redis_cli.get(uuid)
        # If the redis database does not exist, it means it has expired
        if not redis_image_code:
            return JsonResponse({'code': 400, 'errmsg': 'Verification code expired,Please refresh'})
        # If you take it out, delete the picture verification code in redis to save memory
        try:
            redis_cli.delete(uuid)
        except Exception as e:
            print("Delete picture verification code")
        # Comparison with the picture verification code entered by the user
        if image_code.lower() != redis_image_code.decode().lower():
            return JsonResponse({'code': 400, 'errmsg': 'Incorrect verification code'})

        # Store a variable in redis for 180 seconds. If it exists, return the operation too frequently to avoid sending verification codes frequently
        send_flag = redis_cli.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': 'Operation is too frequent'})
        # Create redis pipeline to save time
        pl = redis_cli.pipeline()
        # Get a 6-digit SMS verification code
        sms_code = '%06d' % randint(0, 999999)
        # Save frequently verified variables and SMS verification codes to redis database
        pl.setex('send_flag_%s' % mobile, 180, 1)
        pl.setex('sms_%s' % mobile, 180, sms_code)
        # Perform operations
        pl.execute()
        # Send SMS to the user's mobile phone, valid for three minutes
        SmsUtil().send_message('1', mobile, (sms_code, '3'))
        # Return success
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

User view to judge whether the SMS verification code is correct
		# redis database takes out the SMS verification code according to the mobile phone number
        redis_cli = get_redis_connection('code')
        redis_sms_code = redis_cli.get('sms_%s' % mobile)
        # If not, the verification code expires
        if not redis_sms_code:
            return JsonResponse({"code": "400", "errmsg": "SMS verification code has expired"})
        # Take out the contrast
        if sms_code != redis_sms_code.decode():
            return JsonResponse({"code": "400", "errmsg": "Incorrect SMS verification code"})
The status in Django remains logged in

create_ When the user creates a user, it returns an object, which is parameter 2 of the login method, and a session ID will be stored in the cookie to maintain the login state

        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # The status is maintained. Parameter 1 is the request and parameter 2 is the return value when creating the user
        login(request, user)

Keywords: Python Django Redis

Added by run2web on Mon, 07 Mar 2022 15:45:22 +0200