In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "Python programming how to use DRF to achieve one-time CAPTCHA OTP", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Python programming how to use DRF to achieve one-time CAPTCHA OTP" this article.
One-time verification code, One Time Password in English, abbreviated as OTP, also known as dynamic password or single valid password, refers to a password that can only be used once on a computer system or other digital device, valid for only one login session or as short as 1 minute. OTP avoids some shortcomings of static password authentication and is not vulnerable to replay attacks, such as common registration scenarios in which users receive an one-time activation link to their mailbox or SMS, or receive a random verification code (which can only be used once), thus verifying the validity of the mailbox or mobile phone number.
The functions to be implemented are:
1. CAPTCHA is a combination of 6-digit numbers and lowercase letters.
2. The validity period is 5 minutes, and the second time to send the CAPTCHA must be 1 minute later.
3. If the mailbox / mobile phone number is already registered, the registration verification code cannot be sent.
The specific implementation logic is:
1. Mr. Cheng is a CAPTCHA that meets the conditions.
2. Verify before sending. Is the last CAPTCHA sent within 1 minute? Is the mailbox registered? If so, refuse to send, and prompt the user, if not, send a CAPTCHA.
3. Verify whether it is the verification code within 5 minutes, whether it is correct, and if so, release it. Otherwise, prompt the user.
In order to verify the CAPTCHA and its validity, we need to record the time when the CAPTCHA was sent and the corresponding mailbox, so we need to design a table to store it.
Class VerifyCode (models.Model): mobile = models.CharField (max_length=11, verbose_name= "mobile number", blank=True) email = models.EmailField (verbose_name= "email", blank=True) code = models.CharField (max_length=8, verbose_name= "CAPTCHA") add_time = models.DateTimeField (verbose_name=' generation time', auto_now_add=True) 1, generate CAPTCHA
The first logic is so simple that you can write the code directly:
From random import choice def generate_code (self): "" generates a 6-digit verification code to prevent cracking: return: "" seeds = "1234567890abcdefghijklmnopqrstuvwxyz" random_str = [] for i in range (6): random_str.append (choice (seeds)) return ".join (random_str) 2, pre-send verification
The Serializer of the Django REST framework framework can verify every field in the Models, and we can fill in the blank questions directly in it:
# serializers.pyclass VerifyCodeSerializer (serializers.Serializer): email = serializers.EmailField (required=True) def validate_email (self Email): "" verify whether the mailbox is legal "" # whether the mailbox is registered with if User.objects.filter (email = email) .count (): raise serializers.ValidationError ('the mailbox is already registered') # verify that the mailbox number is legal if not re.match (EMAIL_REGEX Email): raise serializers.ValidationError ('incorrect mailbox format') # CAPTCHA sending frequency one_minute_age = datetime.now ()-timedelta (hours=0, minutes=1, seconds=0) if VerifyCode.objects.filter (add_time__gt=one_minute_age, email=email) .count (): raise serializers.ValidationError ('Please send again in a minute') return email3, send CAPTCHA
Sending CAPTCHA is actually the process of generating CAPTCHA and saving it. With the help of GenericViewSet and CreateModelMixin of the Django REST framework framework, the view class can be implemented. The code is annotated in detail, and you can easily understand it:
From rest_framework.response import Responsefrom rest_framework.views import statusfrom rest_framework import mixins, viewsetsclass VerifyCodeViewSet (viewsets.GenericViewSet Mixins.CreateModelMixin): "send CAPTCHA" permission_classes = [AllowAny] # allows everyone to register the pre-send verification logic def generate_code (self) related to serializer_class = VerifyCodeSerializer #: "" generate a 6-digit CAPTCHA to prevent cracking: return: "" seeds = "1234567890abcdefghijklmnopqrstuvwxyz" random _ str = [] for i in range (6): random_str.append (choice (seeds)) return "" .join (random_str) def create (self Request, * args * * kwargs): # content of custom create () serializer = self.get_serializer (data=request.data) serializer.is_valid (raise_exception=True) # this step is equivalent to pre-send verification # get mobile email from validated_data = serializer.validated_data ["email"] # randomly generate code code = self.generate_code () # send SMS or email verification code sms_status = SendVerifyCode.send_email_code (code=code To_email_adress=email) if sms_status = = 0: # logging return Response ({"msg": "email failed"}, status=status.HTTP_400_BAD_REQUEST) else: code_record = VerifyCode (code=code) Email=email) # Save CAPTCHA code_record.save () return Response ({"msg": F "CAPTCHA has been sent to {email} complete", status=status.HTTP_201_CREATED)
The implementation of SendVerifyCode.send_email_code is as follows:
# encoding=utf-8from django.core.mail import send_mailclass SendVerifyCode (object): @ staticmethod def send_email_code (code,to_email_adress): try: success_num = send_mail (subject='xxx system verification code', message=f' your verification code is [code]]. If you don't do it yourself, please ignore it.' , from_email='xxxx@163.com',recipient_list = [to_email_adress], fail_silently=False) return success_num except: return 04, verification at registration
User registration for the database means that the User class inserts a record, that is, the create operation of the view class of User to implement the registration.
From .serializers import UserRegisterSerializer, UserSerializerclass UserViewSet (viewsets.ModelViewSet): "" API endpoint that allows users to be viewed or edited. "" Serializer_class = UserSerializer def get_serializer_class (self): if self.action = = "create": # if you are creating a user, use UserRegisterSerializer serializer_class = UserRegisterSerializer else: serializer_class = UserSerializer return serializer_class
Now that the skeleton is ready, let's write the UserRegisterSerializer class to verify at registration time:
# serializers.pyclass UserRegisterSerializer (serializers.ModelSerializer): # error_message: custom error message format code = serializers.CharField (required=True, allow_blank=False, min_length=6, max_length=6, help_text=' CAPTCHA', error_messages= {'blank':' Please enter CAPTCHA' 'required':' Please enter verification code', 'min_length':' verification code format error', 'max_length':' verification code format error',} Write_only=True) # use validators in drf to verify that username is unique username = serializers.CharField (required=True, allow_blank=False, validators= [UniqueValidator (queryset=User.objects.all (), message=' user already exists')]) email = serializers.EmailField (required=True, allow_blank=False, validators= [UniqueValidator (queryset=User.objects.all ()) Message=' mailbox has been registered')]) # separately validate the code field (validate_+ field name) def validate_code (self Code): verify_records = VerifyCode.objects.filter (email=self.initial_data ['email']). Order_by ('-add_time') if verify_records: last_record = verify_records [0] # determine whether the verification code expires five_minutes_ago = datetime.now ()-timedelta (hours=0, minutes=5 Seconds=0) # get the time 5 minutes ago if last_record.add_time < five_minutes_ago: raise serializers.ValidationError ('CAPTCHA expired') # determine whether CAPTCHA is correct if last_record.code! = code: raise serializers.ValidationError ('CAPTCHA error') # No need to return code to the database Just verify # return code else: raise serializers.ValidationError ('CAPTCHA does not exist') # attrs: the total dict def validate after each field validate (self Attrs): # attrs ['mobile'] = attrs [' username'] # remove the code field del attrs ['code'] return attrs class Meta: model = User fields = (' username', 'email',' password', 'code') extra_kwargs = {' password': {'write_only': True}} def create (self) from attrs Validated_data): user = User (email=validated_data ['email'], username=validated_data [' username']) user.set_password (validated_data ['password']) user.save () return user above are all the contents of the article "how to use DRF to implement one-time CAPTCHA OTP in Python programming" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.