django项目之登录注册页面集成腾讯防水墙验证

一、python后台服务API接入文档:https://007.qq.com/python-access.html?ADTAG=acces.start

二、后台集成:

  1、在users 得视图文件中写入:

from django.shortcuts import render
from rest_framework.views import APIView
from django.conf import settings
from urllib.parse import urlencode
from urllib.request import urlopen
from rest_framework.response import Response
from rest_framework import status
import json
# Create your views here.


class TCaptchaAPIView(APIView):
    def get(self, request):
        AppSecretKey = settings.TENCENT_CAPTCHA.get("App_Secret_Key")
        appid = settings.TENCENT_CAPTCHA.get("APPID")
        Ticket = request.data.get("ticket")
        Randstr = request.data.get("randstr")
        UserIP = request._request.META.get("REMOTE_ADDR")
        url = settings.TENCENT_CAPTCHA.get("TC_URL")
        params = {
            "aid": appid,
            "AppSecretKey": AppSecretKey,
            "Ticket": Ticket,
            "Randstr": Randstr,
            "UserIP": UserIP
        }
        params = urlencode(params)
        f = urlopen("%s?%s" % (url, params))
        content = f.read()
        res = json.loads(content)
        if res:
            error_code = res["response"]
            if error_code == "1":
                return Response({"message": "验证通过"}, status=status.HTTP_200_OK)
            else:
                return Response({"message": "验证失败"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"message": "验证失败"}, status=status.HTTP_400_BAD_REQUEST)

  2、所需要得信息,均存储在dev配置文件中:

TENCENT_CAPTCHA = {
    "APPID": "2095725424",
    "App_Secret_Key": "0dW4OcdXoDMjk0mWWdAW4_Q**",
    "TC_URL": "https://ssl.captcha.qq.com/ticket/verify",
}

  3、在urls文件中,注册路由:

urlpatterns = [
    ...
    path('captcha/', views.TCaptchaAPIView.as_view())
]

三、前端配置:

  1、在需要得文档中加入如下代码:我的配置在login.vue文show_captcha(){

                //判断手机号、密码不为空才继续往下走
                if(this.account.length<1 || this.password.length<1){
                    return false
                }
                let self = this;
                var captcha1 = new TencentCaptcha(this.$settings.appId, function(res) {
                    if(res.ret === 1){
                        //ret == 1 表示验证通过
                        self.$axios.get(`${self.$settings.Host}/users/captcha/`,{
                            params:{
                   ticket: res.ticket,
                   randstr: res.randstr
                   }
}).then(response=>{ self.LoginHandler() }).catch(error=>{ self.$message.error(error.response.data) }) } }); captcha1.show() }

    appId配置在src下面得settings.js文件中

export default {
  ...
  appId: "2095725424",
}
世间安得双全法,不负如来不负卿
原文地址:https://www.cnblogs.com/shangguanruoling/p/12158109.html